diff --git a/Assets/gamedb/gamedb.txt b/Assets/gamedb/gamedb.txt index 530bdd872a..04918082b0 100644 --- a/Assets/gamedb/gamedb.txt +++ b/Assets/gamedb/gamedb.txt @@ -270,6 +270,7 @@ sha1:81D72ACD08A6255AE44639D40D6D90C1EFCF61AF B 77-in-1 (NT141) [p1][b1] NES bo sha1:1C3771B7F116F439D684D04DF792570271C93F86 75 Bingo (Sachen-English) [U] NES board=Sachen_CNROM sha1:4097D5A814308E39D592466B60B64862699CC22A 2-in-1 - Yuu Yuu + Dragonball Z [p1][!] NES board=MAPPER023_BMC sha1:4C499A857087E6C121522435786792A2E4105AC1 Fuuun Shaolin Kyo (FDS Conversion) (Unl) [U][!] NES board=UNIF_UNL-LH10;WRAM=8;VRAM=8 +sha1:CAAC1E829133851648BA7C7CD6EAA7D26A464999 Metal Fighter (Asia) (Unl) (Sachen) NES board=UNIF_UNL-SA-016-1M;PRG=32;CHR=32;PAD_V=0;PAD_H=1 ;;;;;;;;;;;;;;;;;;;----------------------------------------------------------------------- ;;;;;;;;;;;;;;;;;;;----------------------------------------------------------------------- @@ -294,6 +295,7 @@ sha1:6143D80047FFC17C752078C622A44C3E0CB7466E B Dong Fang de Chuan Shuo The Hyru sha1:CEFEBA536DB507DBDEF8A538F9C332D7A75BF613 You Ling Xing Dong (Ch) NES board=MAPPER192;VRAM=4 sha1:DBFCC70CC2DEC7A889429ED542267F0F1BD967BF Ying Xiong Chuan Qi (Ch) NES board=MAPPER224 sha1:FFB4706E49B826C6CDD12E502E8AE94FC9810B7F Monty no Doki Doki Daisassou (FDS Conversion) (Unl) [U][!] NES board=UNIF_UNL-LH32;WRAM=8;VRAM=8;PAD_H=1 +sha1:17473C223453D2D80FCB9DCFA317947287DC5C52 Xing He Zhan Shi (China) (Unl) NES board=WAIXINGMAPPER176 ;wrong vram info sha1:32D71DD6C5A8D78A918FE1B9D6D6C4A570D9652D Oeka Kids Anpanman no Hiragana Daisuki (J) NES board=MAPPER096;VRAM=32 diff --git a/Assets/gamedb/gamedb_a7800.txt b/Assets/gamedb/gamedb_a7800.txt new file mode 100644 index 0000000000..5515b75bdc --- /dev/null +++ b/Assets/gamedb/gamedb_a7800.txt @@ -0,0 +1,156 @@ +;;NOTE: These hashes were generated using trimmed ROM headers +md5:4332c24e4f3bc72e7fe1b77adf66c2b7 3D Asteroids A78 NTSC=true;board=0 +md5:0be996d25144966d5541c9eb4919b289 Ace of Aces A78 NTSC=true;board=A78SG +md5:aadde920b3aaba03bc10b40bd0619c94 Ace of Aces A78 PAL=true;board=A78SG +md5:877dcc97a775ed55081864b2dbf5f1e2 Alien Brigade A78 NTSC=true;board=A78S9 +md5:de3e9496cb7341f865f27e5a72c7f2f5 Alien Brigade A78 PAL=true;board=A78S9 +md5:0a9e58ef5eb9ff93246e0fff684dc7f1 Arkanoid (0911) A78 NTSC=true;board=A7832P +md5:f9fb84658c5586df159a0c75cc46b54c Asteroids Deluxe A78 NTSC=true;board=0 +md5:a65f79ad4a0bbdecd59d5f7eb3623fd7 Asteroids Deluxe A78 NTSC=true;board=A7832 +md5:1baf41de200f26ec643625021290bec2 Asteroids Deluxe A78 PAL=true;board=A7832 +md5:07342c78619ba6ffcc61c10e907e3b50 Asteroids A78 NTSC=true;board=0 +md5:8fc3a695eaea3984912d98ed4a543376 Ballblazer A78 NTSC=true;board=A7832P +md5:b558814d54904ce0582e2f6a801d03af Ballblazer A78 PAL=true;board=A7832P +md5:42682415906c21c6af80e4198403ffda Barnyard Blaster A78 NTSC=true;board=A78SG +md5:babe2bc2976688bafb8b23c192658126 Barnyard Blaster A78 PAL=true;board=A78SG +md5:f5f6b69c5eb4b55fc163158d1a6b423e Basketbrawl A78 NTSC=true;board=A78SG +md5:fba002089fcfa176454ab507e0eb76cb Basketbrawl A78 PAL=true;board=A78SG +md5:6010a398070dfacb4c0173d75d73c50a Beef Drop A78 NTSC=true;board=0 +md5:c534db0a062225b17cfb8ecce0fb9090 Beef Drop A78 NTSC=true;board=0 +md5:6da5b1b9fa0001e3517f6084ff651b07 Bentley Bear - Crystal Quest A78 NTSC=true;board=A78S9 +md5:5a09946e57dbe30408a8f253a28d07db Centipede A78 NTSC=true;board=0 +md5:38c056a48472d9a9e16ebda5ed91dae7 Centipede A78 PAL=true;board=0 +md5:93e4387864b014c155d7c17877990d1e Choplifter! A78 NTSC=true;board=0 +md5:59d4edb0230b5acc918b94f6bc94779f Choplifter! A78 PAL=true;board=0 +md5:441ac404cdc7bcbd4d787f911df7bf0d Color Test A78 NTSC=true;board=0 +md5:2e8e28f6ad8b9b9267d518d880c73ebb Commando A78 NTSC=true;board=A78SGP +md5:55da6c6c3974d013f517e725aa60f48e Commando A78 PAL=true;board=A78SGP +md5:db691469128d9a4217ec7e315930b646 Crack'ed A78 NTSC=true;board=A78SG +md5:7cbe78fa06f47ba6516a67a4b003c9ee Crack'ed A78 PAL=true;board=A78SG +md5:0c9b124355d5328697a3b9e0011353f2 Crazy Brix A78 NTSC=true;board=A7816 +md5:45e1d527becc96d1715e810d1c07ac27 Crazy Brix A78 NTSC=true;board=A7816 +md5:fc7db1a9243ce2140f716762b8352a5c Crazy Brix A78 PAL=true;board=A7816 +md5:a94e4560b6ad053a1c24e096f1262ebf Crossbow A78 NTSC=true;board=A78S9 +md5:63db371d67a98daec547b2abd5e7aa95 Crossbow A78 PAL=true;board=A78S9 +md5:179b76ff729d4849b8f66a502398acae CDark Chambers A78 NTSC=true;board=A78SG +md5:a2b8e2f159642c4b91de82e9a2928494 Dark Chambers A78 PAL=true;board=A78SG +md5:95ac811c7d27af0032ba090f28c107bd Desert Falcon A78 NTSC=true;board=0 +md5:2d5d99b993a885b063f9f22ce5e6523d Desert Falcon A78 PAL=true;board=0 +md5:731879ea82fc0ca245e39e036fe293e6 Dig Dug A78 NTSC=true;board=0 +md5:408dca9fc40e2b5d805f403fa0509436 Dig Dug A78 PAL=true;board=0 +md5:5e332fbfc1e0fc74223d2e73271ce650 Donkey Kong Junior A78 NTSC=true;board=0 +md5:4dc5f88243250461bd61053b13777060 Donkey Kong Junior A78 PAL=true;board=0 +md5:19f1ee292a23636bd57d408b62de79c7 Donkey Kong A78 NTSC=true;board=0 +md5:8e96ef14ce9b5d84bcbc996b66d6d4c7 Donkey Kong A78 PAL=true;board=0 +md5:de2ebafcf0e37aaa9d0e9525a7f4dd62 Double Dragon A78 PAL=true;board=A78AC +md5:543484c00ba233736bcaba2da20eeea9 Double Dragon A78 NTSC=true;board=A78AC +md5:2251a6a0f3aec84cc0aff66fc9fa91e8 F-18 Hornet A78 NTSC=true;board=A78AB +md5:e7709da8e49d3767301947a0a0b9d2e6 F-18 Hornet A78 PAL=true;board=A78AB +md5:6287727ab36391a62f728bbdee88675c FailSafe A78 NTSC=true;board=A7848 +md5:d2bb22f704f1610a4c396c51f5188e15 FailSafe A78 NTSC=true;board=A7848 +md5:d25d5d19188e9f149977c49eb0367cd1 Fatal Run A78 NTSC=true;board=A78SG +md5:23505651ac2e47f3637152066c3aa62f Fatal Run A78 PAL=true;board=A78SG +md5:e80f24e953563e6b61556737d67d3836 Fight Night A78 PAL=true;board=A78SG +md5:07dbbfe612a0a28e283c01545e59f25e Fight Night A78 NTSC=true;board=A78SG +md5:cf76b00244105b8e03cdc37677ec1073 Food Fight A78 NTSC=true;board=0 +md5:de0d4f5a9bf1c1bddee3ed2f7ec51209 Food Fight A78 PAL=true;board=0 +md5:45136d1d9eddf0bebad32995647b3298 Frogger Demo A78 NTSC=true;board=0 +md5:fb8d803b328b2e442548f7799cfa9a4a Galaga A78 NTSC=true;board=0 +md5:f5dc7dc8e38072d3d65bd90a660148ce Galaga A78 PAL=true;board=0 +md5:06204dadc975be5e5e37e7cc66f984cf Gato A78 NTSC=true;board=0 +md5:0baec96787ce17f390e204de1a136e59 Hat Trick A78 PAL=true;board=0 +md5:fd9e78e201b6baafddfd3e1fbfe6ba31 Hat Trick A78 NTSC=true;board=0 +md5:c3672482ca93f70eafd9134b936c3feb Ikari Warriors A78 NTSC=true;board=A78SG +md5:8c2c2a1ea6e9a928a44c3151ba5c1ce3 Ikari Warriors A78 PAL=true;board=A78SG +md5:1745feadabb24e7cefc375904c73fa4c Impossible Mission Fixed A78 NTSC=true;board=A78SGR +md5:baebc9246c087e893dfa489632157180 Impossible Mission A78 NTSC=true;board=A78SGR +md5:80dead01ea2db5045f6f4443faa6fce8 Impossible Mission A78 PAL=true;board=A78SGR +md5:045fd12050b7f2b842d5970f2414e912 Jinks A78 NTSC=true;board=A78SGR +md5:dfb86f4d06f05ad00cf418f0a59a24f7 Jinks A78 PAL=true;board=A78SGR +md5:f18b3b897a25ab3885b43b4bd141b396 Joust A78 NTSC=true;board=0 +md5:f2dae0264a4b4a73762b9d7177e989f6 Joust A78 PAL=true;board=0 +md5:548ba2e54e4fc45ab84ed634d702c136 Jr. Ms. Pac-Man A78 NTSC=true;board=A7832P +md5:6bc2daeb48e28d103a4298a276e7e551 Jr. Pac-Man (Tunnels) A78 NTSC=true;board=A7832P +md5:0b3baf47886915dd2eec5da7671bfa63 Jr. Pac-Man A78 NTSC=true;board=A78SGR +md5:8281ab17fa3bfc0a6c497d6a4f350061 Jr. Pac-Man A78 NTSC=true;board=A78SGR +md5:17b3b764d33eae9b5260f01df7bb9d2f KLAX A78 NTSC=true;board=A78SG +md5:5e0a1e832bbcea6facb832fde23a440a Karateka A78 PAL=true;board=A78S4 +md5:c3a5a8692a423d43d9d28dd5b7d109d9 Karateka A78 NTSC=true;board=0 +md5:f57d0af323d4e173fb49ed447f0563d7 Kung-Fu Master A78 NTSC=true;board=0 +md5:2931b75811ad03f3ac9330838f3d231b Kung-Fu Master A78 PAL=true;board=0 +md5:431ca060201ee1f9eb49d44962874049 Mario Bros. A78 NTSC=true;board=0 +md5:d2e861306be78e44248bb71d7475d8a3 Mario Bros. A78 PAL=true;board=0 +md5:37b5692e33a98115e574185fa8398c22 Mat Mania Challenge A78 NTSC=true;board=A78SG +md5:6819c37b96063b024898a19dbae2df54 Mat Mania Challenge A78 PAL=true;board=A78SG +md5:f2f5e5841e4dda89a2faf8933dc33ea6 Mean 18 Ultimate Golf A78 NTSC=true;board=A78SG +md5:2e9dbad6c0fa381a6cd1bb9abf98a104 Mean 18 Ultimate Golf A78 PAL=true;board=A78SG +md5:bedc30ec43587e0c98fc38c39c1ef9d0 Meltdown A78 NTSC=true;board=A78SG +md5:c80155d7eec9e3dcb79aa6b83c9ccd1e Meltdown A78 PAL=true;board=A78SG +md5:b02f93661f4b7e712810d2bf8e02ad79 Meteor Shower A78 NTSC=true;board=A7816 +md5:2f1f199ecc2b414d28e01f0de53ca8f7 Meteor Shower A78 PAL=true;board=A7816 +md5:bc1e905db1008493a9632aa83ab4682b Midnight Mutants A78 NTSC=true;board=A78SG +md5:6794ea31570eba0b88a0bf1ead3f3f1b Midnight Mutants A78 PAL=true;board=A78SG +md5:017066f522908081ec3ee624f5e4a8aa Missing in Action A78 NTSC=true;board=A78S9 +md5:d0f46bf92ed6e7b1cce63278420cae8a Missing in Action A78 NTSC=true;board=A78S9 +md5:9ff38ea62004201d870caa8bd9463525 Moon Cresta A78 NTSC=true;board=A7832 +md5:3bc8f554cf86f8132a623cc2201a564b Motor Psycho A78 NTSC=true;board=A78SG +md5:5330bfe428a6b601b7e76c2cfc4cd049 Motor Psycho A78 PAL=true;board=A78SG +md5:fc0ea52a9fac557251b65ee680d951e5 Ms. Pac-Man A78 NTSC=true;board=0 +md5:56469e8c5ff8983c6cb8dadc64eb0363 Ms. Pac-Man A78 PAL=true;board=0 +md5:220121f771fc4b98cef97dc040e8d378 Ninja Golf A78 NTSC=true;board=A78SG +md5:ea0c859aa54fe5eaf4c1f327fab06221 Ninja Golf A78 PAL=true;board=A78SG +md5:74569571a208f8b0b1ccfb22d7c914e1 One on One Basketball A78 NTSC=true;board=0 +md5:8dba0425f0262e5704581d8757a1a6e3 One on One Basketball A78 PAL=true;board=0 +md5:5d7bc7092de69095137456733e7b685d Pac-Man Collection A78 NTSC=true;board=0 +md5:90223a8a363bdf643a19d0f97e63b1b2 PacArcade A78 NTSC=true;board=A7816 +md5:386bded4a944bae455fedf56206dd1dd Pete Rose Baseball A78 PAL=true;board=0 +md5:1a5207870dec6fae9111cb747e20d8e3 Pete Rose Baseball A78 NTSC=true;board=0 +md5:05f43244465943ce819780a71a5b572a Pitfighter A78 NTSC=true;board=A78S4 +md5:33aea1e2b6634a1dec8c7006d9afda22 Planet Smashers A78 NTSC=true;board=A78SG +md5:2837a8fd49b7fc7ccd70fd45b69c5099 Planet Smashers A78 PAL=true;board=A78SG +md5:86546808dc60961cdb1b20e761c50ab1 Plutos A78 NTSC=true;board=A78SGR +md5:584582bb09ee8122e7fc09dc7d1ed813 Pole Position II A78 NTSC=true;board=0 +md5:865457e0e0f48253b08f77b9e18f93b2 Pole Position II A78 PAL=true;board=0 +md5:66e7230f7ef9d14db82d76b06b241bc0 Q-bert A78 NTSC=true;board=A7832 +md5:ac03806cef2558fc795a7d5d8dba7bc0 Rampage A78 NTSC=true;board=A78AC +md5:383ed9bd1efb9b6cb3388a777678c928 Realsports Baseball A78 NTSC=true;board=A78S4 +md5:8f7eb10ad0bd75474abf0c6c36c08486 Rescue on Fractalus A78 NTSC=true;board=A7832 +md5:43525a0405184875c2ecfd0196886a34 Rip Off A78 NTSC=true;board=A7816 +md5:106b409c6f4c219b1a3b3d099ead3b2b Rip Off A78 PAL=true;board=0A7816 +md5:505f05e7f161f62ccd749dab3c4a204b Robot Finds Kitten A78 NTSC=true;board=A7832 +md5:66ecaafe1b82ae68ffc96267aaf7a4d7 Robotron 2084 A78 NTSC=true;board=0 +md5:ae85689b21bdf85cb9dc57c3b1fec9db Santa Simon A78 NTSC=true;board=A7848 +md5:57651b6c8e62811fab0361cea537b79c Scramble A78 NTSC=true;board=0 +md5:c265cfd65534a4514f226cb4c7f7d6bf Scramble A78 NTSC=true;board=0 +md5:1ee26fc6b06b4c9ba74931914b7e719d Scramble A78 PAL=true;board=0 +md5:65fe82f419f6583a0f9a736242cb303d Scramble A78 PAL=true;board=0 +md5:980c35ae9625773a450aa7ef51751c04 Scrapyard Dog A78 NTSC=true;board=A78SG +md5:53db322c201323fe2ca8f074c0a2bf86 Scrapyard Dog A78 PAL=true;board=A78SG +md5:b697d9c2d1b9f6cb21041286d1bbfa7f Sentinel A78 NTSC=true;board=A78SG +md5:5469b4de0608f23a5c4f98f331c9e75f Sentinel A78 PAL=true;board=A78SG +md5:2d643ac548c40e58c99d0fe433ba4ba0 Sirius A78 NTSC=true;board=A78SGR +md5:a84c1b2300fbfbf21b1c02387f613dad Space Duel A78 PAL=true;board=0 +md5:771cb4609347657f63e6f0eb26036e35 Space Duel A78 NTSC=true;board=A7832 +md5:6adf79558a3d7f5beca1bb8d34337417 Space Invaders A78 NTSC=true;board=0 +md5:cbb0746192540a13b4c7775c7ce2021f Summer Games A78 NTSC=true;board=A78SGR +md5:cc18e3b37a507c4217eb6cb1de8c8538 Super Huey UH-IX A78 NTSC=true;board=0 +md5:162f9c953f0657689cc74ab20b40280f Super Huey UH-IX A78 PAL=true;board=0 +md5:59b5793bece1c80f77b55d60fb39cb94 Super Skateboardin' A78 NTSC=true;board=0 +md5:95d7c321dce8f57623a9c5b4947bb375 Super Skateboardin' A78 PAL=true;board=0 +md5:5c4f752371a523f15e9980fea73b874d Tank Command A78 NTSC=true;board=A78S4 +md5:3bb9c8d9adc912dd7f8471c97445cd8d Titlematch Pro Wrestling A78 PAL=true;board=0 +md5:1af475ff6429a160752b592f0f92b287 Titlematch Pro Wrestling A78 NTSC=true;board=0 +md5:c3903ab01a51222a52197dbfe6538ecf Tomcat F14 A78 NTSC=true;board=0 +md5:682338364243b023ecc9d24f0abfc9a7 Tomcat F14 A78 PAL=true;board=0 +md5:208ef955fa90a29815eb097bce89bace Touchdown Football A78 NTSC=true;board=A78SG +md5:8d64763db3100aadc552db5e6868506a Tower Toppler A78 NTSC=true;board=A78S4R +md5:32a37244a9c6cc928dcdf02b45365aa8 Tower Toppler A78 PAL=true;board=A78S4R +md5:412cc5bfa08bd03244b9c4e8d46cd0a0 Wasp (Standard Edition) A78 NTSC=true;board=A7832 +md5:427cb05d0a1abb068998e2760d77f4fb Water Ski A78 NTSC=true;board=A78S4 +md5:3799d72f78dda2ee87b0ef8bf7b91186 Winter Games A78 NTSC=true;board=A78SGR +md5:6813ffff510f930c867b3f0aba78ac85 Worm (0703) A78 NTSC=true;board=A7816 +md5:05fb699db9eef564e2fe45c568746dbc Xenophobe A78 NTSC=true;board=A78SG +md5:70937c3184f0be33d06f7f4382ca54de Xenophobe A78 PAL=true;board=A78SG +md5:d7dc17379aa25e5ae3c14b9e780c6f6d Xevious A78 NTSC=true;board=0 +md5:b1a9f196ce5f47ca8caf8fa7bc4ca46c Xevious A78 PAL=true;board=0 +md5:ce6fbdc7b037a4efdaf87267f5f292cc b*nQ A78 NTSC=true;board=0 \ No newline at end of file diff --git a/BizHawk.Client.Common/BinarySaveStates.cs b/BizHawk.Client.Common/BinarySaveStates.cs index db6c146628..2554baa941 100644 --- a/BizHawk.Client.Common/BinarySaveStates.cs +++ b/BizHawk.Client.Common/BinarySaveStates.cs @@ -86,8 +86,8 @@ namespace BizHawk.Client.Common } } - public virtual string ReadName => Name; - public virtual string WriteName => Ext != null ? Name + '.' + Ext : Name; + public string ReadName => Name; + public string WriteName => Ext != null ? Name + '.' + Ext : Name; public string Name { get; protected set; } public string Ext { get; protected set; } @@ -203,7 +203,7 @@ namespace BizHawk.Client.Common } } - private static byte[] zipheader = { 0x50, 0x4b, 0x03, 0x04 }; + private static readonly byte[] Zipheader = { 0x50, 0x4b, 0x03, 0x04 }; public static BinaryStateLoader LoadAndDetect(string filename, bool isMovieLoad = false) { var ret = new BinaryStateLoader(); @@ -212,7 +212,7 @@ namespace BizHawk.Client.Common { byte[] data = new byte[4]; fs.Read(data, 0, 4); - if (!data.SequenceEqual(zipheader)) + if (!data.SequenceEqual(Zipheader)) { return null; } diff --git a/BizHawk.Client.Common/ControllerBinding.cs b/BizHawk.Client.Common/ControllerBinding.cs index 4dc638d23c..8b7de3b1ef 100644 --- a/BizHawk.Client.Common/ControllerBinding.cs +++ b/BizHawk.Client.Common/ControllerBinding.cs @@ -100,7 +100,7 @@ namespace BizHawk.Client.Common } // zero 09-mar-2015 - not sure if adding + 1 here is correct.. but... maybe? - var output = (input * multiplier + 10000.0f) * (range.Max - range.Min + 1) / 20000.0f + range.Min; + var output = (((input * multiplier) + 10000.0f) * (range.Max - range.Min + 1) / 20000.0f) + range.Min; // zero 09-mar-2015 - at this point, we should only have integers, since thats all 100% of consoles ever see // if this becomes a problem we can add flags to the range and update GUIs to be able to display floats diff --git a/BizHawk.Client.Common/FirmwareManager.cs b/BizHawk.Client.Common/FirmwareManager.cs index 80dcf8a6b3..91769d02ea 100644 --- a/BizHawk.Client.Common/FirmwareManager.cs +++ b/BizHawk.Client.Common/FirmwareManager.cs @@ -96,8 +96,9 @@ namespace BizHawk.Client.Common return resolved.FilePath; } - public class RealFirmwareReader : IDisposable + private class RealFirmwareReader : IDisposable { + private readonly List _files = new List(); private SHA1 _sha1 = SHA1.Create(); public void Dispose() @@ -117,13 +118,12 @@ namespace BizHawk.Client.Common } rff.Hash = _sha1.Hash.BytesToHexString(); - dict[rff.Hash] = rff; + Dict[rff.Hash] = rff; _files.Add(rff); return rff; } - public readonly Dictionary dict = new Dictionary(); - private readonly List _files = new List(); + public Dictionary Dict { get; } = new Dictionary(); } public void DoScanAndResolve() @@ -184,12 +184,12 @@ namespace BizHawk.Client.Common var hash = fo.Hash; // did we find this firmware? - if (reader.dict.ContainsKey(hash)) + if (reader.Dict.ContainsKey(hash)) { // rad! then we can use it var ri = new ResolutionInfo { - FilePath = reader.dict[hash].FileInfo.FullName, + FilePath = reader.Dict[hash].FileInfo.FullName, KnownFirmwareFile = FirmwareDatabase.FirmwareFilesByHash[hash], Hash = hash, Size = fo.Size diff --git a/BizHawk.Client.Common/Global.cs b/BizHawk.Client.Common/Global.cs index 5484bbbc4f..e30c506a2d 100644 --- a/BizHawk.Client.Common/Global.cs +++ b/BizHawk.Client.Common/Global.cs @@ -28,12 +28,10 @@ namespace BizHawk.Client.Common /// public static int SoundMaxBufferDeficitMs; - public static AutofireController AutofireNullControls; - // the movie will be spliced inbetween these if it is present - public static CopyControllerAdapter MovieInputSourceAdapter = new CopyControllerAdapter(); - public static CopyControllerAdapter MovieOutputHardpoint = new CopyControllerAdapter(); - public static MultitrackRewiringControllerAdapter MultitrackRewiringAdapter = new MultitrackRewiringControllerAdapter(); + public static readonly CopyControllerAdapter MovieInputSourceAdapter = new CopyControllerAdapter(); + public static readonly CopyControllerAdapter MovieOutputHardpoint = new CopyControllerAdapter(); + public static readonly MultitrackRewiringControllerAdapter MultitrackRewiringAdapter = new MultitrackRewiringControllerAdapter(); // dont take my word for it, since the final word is actually in RewireInputChain, but here is a guide... // user -> Input -> ActiveController -> UDLR -> StickyXORPlayerInputAdapter -> TurboAdapter(TBD) -> Lua(?TBD?) -> .. @@ -47,26 +45,26 @@ namespace BizHawk.Client.Common public static AutofireController AutoFireController; // the "output" port for the controller chain. - public static CopyControllerAdapter ControllerOutput = new CopyControllerAdapter(); + public static readonly CopyControllerAdapter ControllerOutput = new CopyControllerAdapter(); - public static UD_LR_ControllerAdapter UD_LR_ControllerAdapter = new UD_LR_ControllerAdapter(); + public static readonly UD_LR_ControllerAdapter UD_LR_ControllerAdapter = new UD_LR_ControllerAdapter(); - public static AutoFireStickyXorAdapter AutofireStickyXORAdapter = new AutoFireStickyXorAdapter(); + public static readonly AutoFireStickyXorAdapter AutofireStickyXORAdapter = new AutoFireStickyXorAdapter(); /// /// provides an opportunity to mutate the player's input in an autohold style /// - public static StickyXorAdapter StickyXORAdapter = new StickyXorAdapter(); + public static readonly StickyXorAdapter StickyXORAdapter = new StickyXorAdapter(); /// /// Used to AND to another controller, used for Joypad.Set() /// - public static OverrideAdaptor LuaAndAdaptor = new OverrideAdaptor(); + public static readonly OverrideAdaptor LuaAndAdaptor = new OverrideAdaptor(); /// /// fire off one-frame logical button clicks here. useful for things like ti-83 virtual pad and reset buttons /// - public static ClickyVirtualPadController ClickyVirtualPadController = new ClickyVirtualPadController(); + public static readonly ClickyVirtualPadController ClickyVirtualPadController = new ClickyVirtualPadController(); public static SimpleController MovieOutputController = new SimpleController(); diff --git a/BizHawk.Client.Common/QuickBmpFile.cs b/BizHawk.Client.Common/QuickBmpFile.cs index d4a5f7a5a2..0cf3a1c999 100644 --- a/BizHawk.Client.Common/QuickBmpFile.cs +++ b/BizHawk.Client.Common/QuickBmpFile.cs @@ -5,6 +5,10 @@ using System.Runtime.InteropServices; using BizHawk.Common; using BizHawk.Emulation.Common; +// ReSharper disable InconsistentNaming +// ReSharper disable StyleCop.SA1304 +// ReSharper disable StyleCop.SA1307 +// ReSharper disable StyleCop.SA1401 namespace BizHawk.Client.Common { public class QuickBmpFile @@ -12,23 +16,24 @@ namespace BizHawk.Client.Common #region Structs [StructLayout(LayoutKind.Sequential, Pack = 1)] - class BITMAPFILEHEADER + private class Bitmapfileheader { + public readonly uint bfSize; public ushort bfType; - public uint bfSize; + public ushort bfReserved1; public ushort bfReserved2; public uint bfOffBits; - public BITMAPFILEHEADER() + public Bitmapfileheader() { bfSize = (uint)Marshal.SizeOf(this); } - public static BITMAPFILEHEADER FromStream(Stream s) + public static Bitmapfileheader FromStream(Stream s) { - var ret = GetObject(s); - if (ret.bfSize != Marshal.SizeOf(typeof(BITMAPFILEHEADER))) + var ret = GetObject(s); + if (ret.bfSize != Marshal.SizeOf(typeof(Bitmapfileheader))) { throw new InvalidOperationException(); } @@ -38,9 +43,9 @@ namespace BizHawk.Client.Common } [StructLayout(LayoutKind.Sequential)] - class BITMAPINFOHEADER + private class Bitmapinfoheader { - public uint biSize; + public readonly uint biSize; public int biWidth; public int biHeight; public ushort biPlanes; @@ -52,15 +57,15 @@ namespace BizHawk.Client.Common public uint biClrUsed; public uint biClrImportant; - public BITMAPINFOHEADER() + public Bitmapinfoheader() { biSize = (uint)Marshal.SizeOf(this); } - public static BITMAPINFOHEADER FromStream(Stream s) + public static Bitmapinfoheader FromStream(Stream s) { - var ret = GetObject(s); - if (ret.biSize != Marshal.SizeOf(typeof(BITMAPINFOHEADER))) + var ret = GetObject(s); + if (ret.biSize != Marshal.SizeOf(typeof(Bitmapinfoheader))) { throw new InvalidOperationException(); } @@ -141,18 +146,18 @@ namespace BizHawk.Client.Common { int w = dst.Width; int h = dst.Height; - int in_w = src.Width; - int in_h = src.Height; + int inW = src.Width; + int inH = src.Height; int* sp = src.Data; int* dp = dst.Data; // vflip along the way for (int j = h - 1; j >= 0; j--) { - sp = src.Data + in_w * (j * in_h / h); + sp = src.Data + (inW * (j * inH / h)); for (int i = 0; i < w; i++) { - dp[i] = sp[i * in_w / w]; + dp[i] = sp[i * inW / w]; } dp += w; @@ -163,17 +168,17 @@ namespace BizHawk.Client.Common { int w = dst.Width; int h = dst.Height; - int in_w = src.Width; - int in_h = src.Height; + int inW = src.Width; + int inH = src.Height; int* sp = src.Data; int* dp = dst.Data; for (int j = 0; j < h; j++) { - sp = src.Data + in_w * (j * in_h / h); + sp = src.Data + (inW * (j * inH / h)); for (int i = 0; i < w; i++) { - dp[i] = sp[i * in_w / w]; + dp[i] = sp[i * inW / w]; } dp += w; @@ -239,8 +244,8 @@ namespace BizHawk.Client.Common public static unsafe bool Load(IVideoProvider v, Stream s) { - var bf = BITMAPFILEHEADER.FromStream(s); - var bi = BITMAPINFOHEADER.FromStream(s); + var bf = Bitmapfileheader.FromStream(s); + var bi = Bitmapinfoheader.FromStream(s); if (bf.bfType != 0x4d42 || bf.bfOffBits != bf.bfSize + bi.biSize || bi.biPlanes != 1 @@ -250,17 +255,17 @@ namespace BizHawk.Client.Common return false; } - int in_w = bi.biWidth; - int in_h = bi.biHeight; + int inW = bi.biWidth; + int inH = bi.biHeight; - byte[] src = new byte[in_w * in_h * 4]; + byte[] src = new byte[inW * inH * 4]; s.Read(src, 0, src.Length); if (v is LoadedBMP) { var l = v as LoadedBMP; - l.BufferWidth = in_w; - l.BufferHeight = in_h; - l.VideoBuffer = new int[in_w * in_h]; + l.BufferWidth = inW; + l.BufferHeight = inH; + l.VideoBuffer = new int[inW * inH]; } int[] dst = v.GetVideoBuffer(); @@ -273,8 +278,8 @@ namespace BizHawk.Client.Common Blit(new BMP { Data = (int*)srcp, - Width = in_w, - Height = in_h + Width = inW, + Height = inH }, new BMP { @@ -290,8 +295,8 @@ namespace BizHawk.Client.Common public static unsafe void Save(IVideoProvider v, Stream s, int w, int h) { - var bf = new BITMAPFILEHEADER(); - var bi = new BITMAPINFOHEADER(); + var bf = new Bitmapfileheader(); + var bi = new Bitmapinfoheader(); bf.bfType = 0x4d42; bf.bfOffBits = bf.bfSize + bi.biSize; diff --git a/BizHawk.Client.Common/RomLoader.cs b/BizHawk.Client.Common/RomLoader.cs index c0d2e21ab1..a49d41d7c3 100644 --- a/BizHawk.Client.Common/RomLoader.cs +++ b/BizHawk.Client.Common/RomLoader.cs @@ -7,6 +7,7 @@ using BizHawk.Common; using BizHawk.Emulation.Common; using BizHawk.Emulation.Cores; using BizHawk.Emulation.Cores.Libretro; +using BizHawk.Emulation.Cores.Atari.A7800Hawk; using BizHawk.Emulation.Cores.Atari.Atari7800; using BizHawk.Emulation.Cores.Calculators; using BizHawk.Emulation.Cores.Computers.AppleII; @@ -569,6 +570,7 @@ namespace BizHawk.Client.Common nextEmulator = new C64( nextComm, xmlGame.Assets.Select(a => a.Value), + GameInfo.NullInstance, (C64.C64Settings)GetCoreSettings(), (C64.C64SyncSettings)GetCoreSyncSettings()); break; @@ -835,14 +837,16 @@ namespace BizHawk.Client.Common break; case "A78": var gamedbpath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "EMU7800.csv"); - nextEmulator = new Atari7800(nextComm, game, rom.RomData, gamedbpath); + + nextEmulator = Global.Config.A78_UseEmu7800 + ? nextEmulator = new Atari7800(nextComm, game, rom.RomData, gamedbpath) + : nextEmulator = new A7800Hawk(nextComm, game, rom.RomData, gamedbpath); break; case "C64": - var c64 = new C64(nextComm, Enumerable.Repeat(rom.RomData, 1), GetCoreSettings(), GetCoreSyncSettings()); + var c64 = new C64(nextComm, Enumerable.Repeat(rom.RomData, 1), rom.GameInfo, GetCoreSettings(), GetCoreSyncSettings()); nextEmulator = c64; break; case "GBA": - // core = CoreInventory.Instance["GBA", "Meteor"]; if (Global.Config.GBA_UsemGBA) { core = CoreInventory.Instance["GBA", "mGBA"]; diff --git a/BizHawk.Client.Common/SavestateManager.cs b/BizHawk.Client.Common/SavestateManager.cs index 68efe213d6..8f250bc135 100644 --- a/BizHawk.Client.Common/SavestateManager.cs +++ b/BizHawk.Client.Common/SavestateManager.cs @@ -62,7 +62,7 @@ namespace BizHawk.Client.Common using (new SimpleTime("Save Framebuffer")) { - bs.PutLump(BinaryStateLump.Framebuffer, (s) => QuickBmpFile.Save(Global.Emulator.AsVideoProvider(), s, out_w, out_h)); + bs.PutLump(BinaryStateLump.Framebuffer, s => QuickBmpFile.Save(Global.Emulator.AsVideoProvider(), s, out_w, out_h)); } } } diff --git a/BizHawk.Client.Common/SevenZipWriter.cs b/BizHawk.Client.Common/SevenZipWriter.cs index 7e34127849..de14457e9f 100644 --- a/BizHawk.Client.Common/SevenZipWriter.cs +++ b/BizHawk.Client.Common/SevenZipWriter.cs @@ -10,19 +10,20 @@ namespace BizHawk.Client.Common { private class RangBuffer { - const int LEN = 4096; - const int MASK = 4095; - byte[] buff = new byte[LEN]; + private const int Len = 4096; + private const int Mask = 4095; - int wpos = 0; - int rpos = 0; + private readonly byte[] _buff = new byte[Len]; - bool writeclosed; - bool readclosed; + private readonly object _sharedlock = new object(); + private readonly ManualResetEvent _full = new ManualResetEvent(true); + private readonly ManualResetEvent _empty = new ManualResetEvent(false); - object sharedlock = new object(); - ManualResetEvent full = new ManualResetEvent(true); - ManualResetEvent empty = new ManualResetEvent(false); + private int _wpos; + private int _rpos; + + private bool _writeclosed; + private bool _readclosed; public Stream W { get; } public Stream R { get; } @@ -38,23 +39,23 @@ namespace BizHawk.Client.Common // slow, but faster than using the other overload with byte[1] while (true) { - empty.WaitOne(); - lock (sharedlock) + _empty.WaitOne(); + lock (_sharedlock) { - if (rpos != wpos) + if (_rpos != _wpos) { - byte ret = buff[rpos++]; - rpos &= MASK; - full.Set(); + byte ret = _buff[_rpos++]; + _rpos &= Mask; + _full.Set(); return ret; } - else if (writeclosed) + else if (_writeclosed) { return -1; } else { - empty.Reset(); + _empty.Reset(); } } } @@ -65,14 +66,14 @@ namespace BizHawk.Client.Common int ret = 0; while (count > 0) { - empty.WaitOne(); - lock (sharedlock) + _empty.WaitOne(); + lock (_sharedlock) { - int start = rpos; - int end = wpos; + int start = _rpos; + int end = _wpos; if (end < start) // wrap { - end = LEN; + end = Len; } if (end - start > count) @@ -83,20 +84,20 @@ namespace BizHawk.Client.Common int c = end - start; if (c > 0) { - Buffer.BlockCopy(buff, start, buffer, offset, c); + Buffer.BlockCopy(_buff, start, buffer, offset, c); count -= c; ret += c; offset += c; - rpos = end & MASK; - full.Set(); + _rpos = end & Mask; + _full.Set(); } - else if (writeclosed) + else if (_writeclosed) { break; } else { - empty.Reset(); + _empty.Reset(); } } } @@ -106,10 +107,10 @@ namespace BizHawk.Client.Common public void CloseRead() { - lock (sharedlock) + lock (_sharedlock) { - readclosed = true; - full.Set(); + _readclosed = true; + _full.Set(); } } @@ -117,25 +118,24 @@ namespace BizHawk.Client.Common { while (true) { - full.WaitOne(); - lock (sharedlock) + _full.WaitOne(); + lock (_sharedlock) { - int next = (wpos + 1) & MASK; - if (next != rpos) + int next = (_wpos + 1) & Mask; + if (next != _rpos) { - buff[wpos] = value; - wpos = next; - empty.Set(); + _buff[_wpos] = value; + _wpos = next; + _empty.Set(); return true; } - else if (readclosed) + + if (_readclosed) { return false; } - else - { - full.Reset(); - } + + _full.Reset(); } } } @@ -145,14 +145,14 @@ namespace BizHawk.Client.Common int ret = 0; while (count > 0) { - full.WaitOne(); - lock (sharedlock) + _full.WaitOne(); + lock (_sharedlock) { - int start = wpos; - int end = (rpos - 1) & MASK; + int start = _wpos; + int end = (_rpos - 1) & Mask; if (end < start) // wrap { - end = LEN; + end = Len; } if (end - start > count) @@ -163,20 +163,20 @@ namespace BizHawk.Client.Common int c = end - start; if (c > 0) { - Buffer.BlockCopy(buffer, offset, buff, start, c); + Buffer.BlockCopy(buffer, offset, _buff, start, c); count -= c; ret += c; offset += c; - wpos = end & MASK; - empty.Set(); + _wpos = end & Mask; + _empty.Set(); } - else if (readclosed) + else if (_readclosed) { break; } else { - full.Reset(); + _full.Reset(); } } } @@ -186,10 +186,10 @@ namespace BizHawk.Client.Common public void CloseWrite() { - lock (sharedlock) + lock (_sharedlock) { - writeclosed = true; - empty.Set(); + _writeclosed = true; + _empty.Set(); } } @@ -262,11 +262,12 @@ namespace BizHawk.Client.Common private class RStream : Stream { - public override bool CanRead { get { return true; } } - public override bool CanSeek { get { return false; } } - public override bool CanWrite { get { return false; } } + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override void Flush() { } - public override long Length { get { return 1; } } // { get { throw new NotSupportedException(); } } + public override long Length => 1; // { get { throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { return 0; } // { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override long Position @@ -328,43 +329,43 @@ namespace BizHawk.Client.Common } } - private SevenZip.SevenZipCompressor svc; + private readonly SevenZip.SevenZipCompressor _svc; + private readonly string _path; - private bool first = true; - private string path; - private int compressionlevel; + private bool _first = true; + private int _compressionlevel; public SevenZipWriter(string path, int compressionlevel) { - this.path = path; - this.compressionlevel = compressionlevel; + _path = path; + _compressionlevel = compressionlevel; - svc = new SevenZip.SevenZipCompressor { ArchiveFormat = SevenZip.OutArchiveFormat.Zip }; + _svc = new SevenZip.SevenZipCompressor { ArchiveFormat = SevenZip.OutArchiveFormat.Zip }; switch (compressionlevel) { default: case 0: - svc.CompressionLevel = SevenZip.CompressionLevel.None; + _svc.CompressionLevel = SevenZip.CompressionLevel.None; break; case 1: case 2: - svc.CompressionLevel = SevenZip.CompressionLevel.Fast; + _svc.CompressionLevel = SevenZip.CompressionLevel.Fast; break; case 3: case 4: - svc.CompressionLevel = SevenZip.CompressionLevel.Low; + _svc.CompressionLevel = SevenZip.CompressionLevel.Low; break; case 5: case 6: - svc.CompressionLevel = SevenZip.CompressionLevel.Normal; + _svc.CompressionLevel = SevenZip.CompressionLevel.Normal; break; case 7: case 8: - svc.CompressionLevel = SevenZip.CompressionLevel.High; + _svc.CompressionLevel = SevenZip.CompressionLevel.High; break; case 9: - svc.CompressionLevel = SevenZip.CompressionLevel.Ultra; + _svc.CompressionLevel = SevenZip.CompressionLevel.Ultra; break; } } @@ -374,19 +375,19 @@ namespace BizHawk.Client.Common var dict = new Dictionary(); var r = new RangBuffer(); dict[name] = r.R; - if (first) + if (_first) { - first = false; - svc.CompressionMode = SevenZip.CompressionMode.Create; + _first = false; + _svc.CompressionMode = SevenZip.CompressionMode.Create; } else { - svc.CompressionMode = SevenZip.CompressionMode.Append; + _svc.CompressionMode = SevenZip.CompressionMode.Append; } var task = Task.Factory.StartNew(() => { - svc.CompressStreamDictionary(dict, path); + _svc.CompressStreamDictionary(dict, _path); }); try { diff --git a/BizHawk.Client.Common/SystemInfo.cs b/BizHawk.Client.Common/SystemInfo.cs index 5039adcdc3..3ca1864a30 100644 --- a/BizHawk.Client.Common/SystemInfo.cs +++ b/BizHawk.Client.Common/SystemInfo.cs @@ -206,7 +206,7 @@ namespace BizHawk.Client.Common } /// - /// Gets the haschode for current insance + /// Gets the haschode for current instance /// /// This instance hashcode public override int GetHashCode() @@ -241,7 +241,7 @@ namespace BizHawk.Client.Common /// /// First /// Second - /// True if both system are diferent; otherwise, false + /// True if both system are different; otherwise, false public static bool operator !=(SystemInfo system1, SystemInfo system2) { return !(system1 == system2); diff --git a/BizHawk.Client.Common/XmlGame.cs b/BizHawk.Client.Common/XmlGame.cs index c896f7e1c5..3926322672 100644 --- a/BizHawk.Client.Common/XmlGame.cs +++ b/BizHawk.Client.Common/XmlGame.cs @@ -13,17 +13,10 @@ namespace BizHawk.Client.Common { public class XmlGame { - public XmlGame() - { - Assets = new List>(); - AssetFullPaths = new List(); - GI = new GameInfo(); - } - public XmlDocument Xml { get; set; } - public GameInfo GI { get; } - public IList> Assets { get; } - public IList AssetFullPaths { get; } // TODO: Hack work around, to avoid having to refactor Assets into a object array, should be refactored! + public GameInfo GI { get; } = new GameInfo(); + public IList> Assets { get; } = new List>(); + public IList AssetFullPaths { get; } = new List(); // TODO: Hack work around, to avoid having to refactor Assets into a object array, should be refactored! public static XmlGame Create(HawkFile f) { @@ -52,8 +45,8 @@ namespace BizHawk.Client.Common var n = y.SelectSingleNode("./LoadAssets"); if (n != null) { - var HashStream = new MemoryStream(); - int? OriginalIndex = null; + var hashStream = new MemoryStream(); + int? originalIndex = null; foreach (XmlNode a in n.ChildNodes) { @@ -65,9 +58,9 @@ namespace BizHawk.Client.Common var ai = f.FindArchiveMember(filename.Substring(1)); if (ai != null) { - if (OriginalIndex == null) + if (originalIndex == null) { - OriginalIndex = f.GetBoundIndex(); + originalIndex = f.GetBoundIndex(); } f.Unbind(); @@ -112,16 +105,16 @@ namespace BizHawk.Client.Common using (var sha1 = System.Security.Cryptography.SHA1.Create()) { sha1.TransformFinalBlock(data, 0, data.Length); - HashStream.Write(sha1.Hash, 0, sha1.Hash.Length); + hashStream.Write(sha1.Hash, 0, sha1.Hash.Length); } } - ret.GI.Hash = HashStream.GetBuffer().HashSHA1(0, (int)HashStream.Length); - HashStream.Close(); - if (OriginalIndex != null) + ret.GI.Hash = hashStream.GetBuffer().HashSHA1(0, (int)hashStream.Length); + hashStream.Close(); + if (originalIndex != null) { f.Unbind(); - f.BindArchiveMember((int)OriginalIndex); + f.BindArchiveMember((int)originalIndex); } } else diff --git a/BizHawk.Client.Common/config/Binding.cs b/BizHawk.Client.Common/config/Binding.cs index 029a7fde41..6cc7bf552f 100644 --- a/BizHawk.Client.Common/config/Binding.cs +++ b/BizHawk.Client.Common/config/Binding.cs @@ -15,12 +15,12 @@ namespace BizHawk.Client.Common { public class Binding { - public string DisplayName; - public string Bindings; - public string DefaultBinding; - public string TabGroup; - public string ToolTip; - public int Ordinal = 0; + public string DisplayName { get; set; } + public string Bindings { get; set; } + public string DefaultBinding { get; set; } + public string TabGroup { get; set; } + public string ToolTip { get; set; } + public int Ordinal { get; set; } } [Newtonsoft.Json.JsonObject] @@ -29,9 +29,9 @@ namespace BizHawk.Client.Common public List Bindings { get; } [Newtonsoft.Json.JsonConstructor] - public BindingCollection(List Bindings) + public BindingCollection(List bindings) { - this.Bindings = Bindings; + Bindings = bindings; } public BindingCollection() @@ -105,15 +105,15 @@ namespace BizHawk.Client.Common } } - private static List s_DefaultValues; + private static List _defaultValues; public static List DefaultValues { get { - if (s_DefaultValues == null) + if (_defaultValues == null) { - s_DefaultValues = new List + _defaultValues = new List { Bind("General", "Frame Advance", "F"), Bind("General", "Rewind", "Shift+R, J1 B7, X1 LeftTrigger"), @@ -261,13 +261,13 @@ namespace BizHawk.Client.Common }; // set ordinals based on order in list - for (int i = 0; i < s_DefaultValues.Count; i++) + for (int i = 0; i < _defaultValues.Count; i++) { - s_DefaultValues[i].Ordinal = i; + _defaultValues[i].Ordinal = i; } } // if (s_DefaultValues == null) - return s_DefaultValues; + return _defaultValues; } } } diff --git a/BizHawk.Client.Common/config/Config.cs b/BizHawk.Client.Common/config/Config.cs index ddb69c9863..88f2b8b98a 100644 --- a/BizHawk.Client.Common/config/Config.cs +++ b/BizHawk.Client.Common/config/Config.cs @@ -537,6 +537,7 @@ namespace BizHawk.Client.Common public bool NES_InQuickNES = true; public bool SNES_InSnes9x = false; public bool GBA_UsemGBA = false; + public bool A78_UseEmu7800 = true; public bool CoreForcingViaGameDB = true; public string LibretroCore; } diff --git a/BizHawk.Client.Common/inputAdapters/AutoPattern.cs b/BizHawk.Client.Common/inputAdapters/AutoPattern.cs index 13d26191ad..eac3c16eb8 100644 --- a/BizHawk.Client.Common/inputAdapters/AutoPattern.cs +++ b/BizHawk.Client.Common/inputAdapters/AutoPattern.cs @@ -2,11 +2,6 @@ { public class AutoPatternBool { - public readonly bool SkipsLag = true; - public readonly bool[] Pattern; - public readonly int Loop = 0; - private int _index = 0; - public AutoPatternBool() { Pattern = new[] { true }; @@ -36,6 +31,12 @@ Loop = loop; } + private int _index; + + public bool SkipsLag { get; } = true; + public bool[] Pattern { get; } + public int Loop { get; } + /// /// Gets the next value and increments index. /// @@ -70,11 +71,6 @@ public class AutoPatternFloat { - public readonly bool SkipsLag = true; - public readonly float[] Pattern; - public readonly int Loop = 0; - private int _index; - /// /// Initializes a new instance of the class. /// Defaults to 0. @@ -85,11 +81,12 @@ } /// + /// Initializes a new instance of the class. /// Simple on/off pattern, using the given values as on/off. /// - public AutoPatternFloat(float valueOn, int on, float valueOff, int off, bool skip_lag = true, int offset = 0, int loop = 0) + public AutoPatternFloat(float valueOn, int on, float valueOff, int off, bool skipLag = true, int offset = 0, int loop = 0) { - SkipsLag = skip_lag; + SkipsLag = skipLag; _index = offset; Loop = loop; Pattern = new float[on + off]; @@ -104,14 +101,20 @@ } } - public AutoPatternFloat(float[] pattern, bool skip_lag = true, int offset = 0, int loop = 0) + public AutoPatternFloat(float[] pattern, bool skipLag = true, int offset = 0, int loop = 0) { - SkipsLag = skip_lag; + SkipsLag = skipLag; Pattern = pattern; _index = offset; Loop = loop; } + private int _index; + + public bool SkipsLag { get; } = true; + public float[] Pattern { get; } + public int Loop { get; } + /// /// Gets the next value and increments index. /// diff --git a/BizHawk.Client.Common/inputAdapters/SimpleController.cs b/BizHawk.Client.Common/inputAdapters/SimpleController.cs index 4f44267885..e38fb133db 100644 --- a/BizHawk.Client.Common/inputAdapters/SimpleController.cs +++ b/BizHawk.Client.Common/inputAdapters/SimpleController.cs @@ -13,8 +13,8 @@ namespace BizHawk.Client.Common { public ControllerDefinition Definition { get; set; } - protected WorkingDictionary Buttons = new WorkingDictionary(); - protected WorkingDictionary Floats = new WorkingDictionary(); + protected WorkingDictionary Buttons { get; private set; } = new WorkingDictionary(); + protected WorkingDictionary Floats { get; private set; } = new WorkingDictionary(); public void Clear() { @@ -43,14 +43,6 @@ namespace BizHawk.Client.Common return Buttons; } - public void LatchFrom(IController source) - { - foreach (var button in source.Definition.BoolButtons) - { - Buttons[button] = source.IsPressed(button); - } - } - public void AcceptNewFloats(IEnumerable> newValues) { foreach (var sv in newValues) diff --git a/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs b/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs index a92d6289dc..bf663c38df 100644 --- a/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs +++ b/BizHawk.Client.Common/inputAdapters/StickyAdapters.cs @@ -58,7 +58,7 @@ namespace BizHawk.Client.Common public bool IsPressed(string button) { var source = Source.IsPressed(button); - source ^= stickySet.Contains(button); + source ^= _stickySet.Contains(button); return source; } @@ -81,15 +81,13 @@ namespace BizHawk.Client.Common public IController Source { get; set; } - public bool Locked { get; set; } // Pretty much a hack, - private List _justPressed = new List(); - protected readonly HashSet stickySet = new HashSet(); + private readonly HashSet _stickySet = new HashSet(); // if SetFloat() is called (typically virtual pads), then that float will entirely override the Source input // otherwise, the source is passed thru. - protected readonly WorkingDictionary _floatSet = new WorkingDictionary(); + private readonly WorkingDictionary _floatSet = new WorkingDictionary(); public void SetFloat(string name, float? value) { @@ -112,30 +110,30 @@ namespace BizHawk.Client.Common { if (isSticky) { - stickySet.Add(button); + _stickySet.Add(button); } else { - stickySet.Remove(button); + _stickySet.Remove(button); } } public void Unset(string button) { - stickySet.Remove(button); + _stickySet.Remove(button); _floatSet.Remove(button); } public bool IsSticky(string button) { - return stickySet.Contains(button); + return _stickySet.Contains(button); } - public HashSet CurrentStickies => stickySet; + public HashSet CurrentStickies => _stickySet; public void ClearStickies() { - stickySet.Clear(); + _stickySet.Clear(); _floatSet.Clear(); } @@ -143,13 +141,13 @@ namespace BizHawk.Client.Common { foreach (var button in buttons.Where(button => !_justPressed.Contains(button))) { - if (stickySet.Contains(button)) + if (_stickySet.Contains(button)) { - stickySet.Remove(button); + _stickySet.Remove(button); } else { - stickySet.Add(button); + _stickySet.Add(button); } } @@ -207,13 +205,13 @@ namespace BizHawk.Client.Common // TODO: Change the AutoHold adapter to be one of these, with an 'Off' value of 0? // Probably would have slightly lower performance, but it seems weird to have such a similar class that is only used once. - private int On; - private int Off; + private int _on; + private int _off; public void SetOnOffPatternFromConfig() { - On = Global.Config.AutofireOn < 1 ? 0 : Global.Config.AutofireOn; - Off = Global.Config.AutofireOff < 1 ? 0 : Global.Config.AutofireOff; + _on = Global.Config.AutofireOn < 1 ? 0 : Global.Config.AutofireOn; + _off = Global.Config.AutofireOff < 1 ? 0 : Global.Config.AutofireOff; } private readonly WorkingDictionary _boolPatterns = new WorkingDictionary(); @@ -221,21 +219,19 @@ namespace BizHawk.Client.Common public AutoFireStickyXorAdapter() { - On = 1; - Off = 1; + _on = 1; + _off = 1; } public IController Source { get; set; } - public bool Locked { get; set; } // Pretty much a hack, - public void SetFloat(string name, float? value, AutoPatternFloat pattern = null) { if (value.HasValue) { if (pattern == null) { - pattern = new AutoPatternFloat(value.Value, On, 0, Off); + pattern = new AutoPatternFloat(value.Value, _on, 0, _off); } _floatPatterns[name] = pattern; @@ -246,18 +242,13 @@ namespace BizHawk.Client.Common } } - public void ClearStickyFloats() - { - _floatPatterns.Clear(); - } - public void SetSticky(string button, bool isSticky, AutoPatternBool pattern = null) { if (isSticky) { if (pattern == null) { - pattern = new AutoPatternBool(On, Off); + pattern = new AutoPatternBool(_on, _off); } _boolPatterns[button] = pattern; @@ -268,12 +259,6 @@ namespace BizHawk.Client.Common } } - public void Unset(string button) - { - _boolPatterns.Remove(button); - _floatPatterns.Remove(button); - } - public bool IsSticky(string button) { return _boolPatterns.ContainsKey(button) || _floatPatterns.ContainsKey(button); diff --git a/BizHawk.Client.Common/inputAdapters/UDLRController.cs b/BizHawk.Client.Common/inputAdapters/UDLRController.cs index e29629cf7d..38222679a3 100644 --- a/BizHawk.Client.Common/inputAdapters/UDLRController.cs +++ b/BizHawk.Client.Common/inputAdapters/UDLRController.cs @@ -28,14 +28,14 @@ namespace BizHawk.Client.Common { if (!Source.IsPressed(button)) { - Unpresses.Remove(button); + _unpresses.Remove(button); } prefix = button.GetPrecedingString("Down"); string other = prefix + "Up"; if (Source.IsPressed(other)) { - if (Unpresses.Contains(button)) + if (_unpresses.Contains(button)) { return false; } @@ -45,11 +45,11 @@ namespace BizHawk.Client.Common return false; } - Unpresses.Add(other); + _unpresses.Add(other); } else { - Unpresses.Remove(button); + _unpresses.Remove(button); } } @@ -57,14 +57,14 @@ namespace BizHawk.Client.Common { if (!Source.IsPressed(button)) { - Unpresses.Remove(button); + _unpresses.Remove(button); } prefix = button.GetPrecedingString("Up"); string other = prefix + "Down"; if (Source.IsPressed(other)) { - if (Unpresses.Contains(button)) + if (_unpresses.Contains(button)) { return false; } @@ -74,11 +74,11 @@ namespace BizHawk.Client.Common return false; } - Unpresses.Add(other); + _unpresses.Add(other); } else { - Unpresses.Remove(button); + _unpresses.Remove(button); } } @@ -86,14 +86,14 @@ namespace BizHawk.Client.Common { if (!Source.IsPressed(button)) { - Unpresses.Remove(button); + _unpresses.Remove(button); } prefix = button.GetPrecedingString("Right"); string other = prefix + "Left"; if (Source.IsPressed(other)) { - if (Unpresses.Contains(button)) + if (_unpresses.Contains(button)) { return false; } @@ -103,11 +103,11 @@ namespace BizHawk.Client.Common return false; } - Unpresses.Add(other); + _unpresses.Add(other); } else { - Unpresses.Remove(button); + _unpresses.Remove(button); } } @@ -115,14 +115,14 @@ namespace BizHawk.Client.Common { if (!Source.IsPressed(button)) { - Unpresses.Remove(button); + _unpresses.Remove(button); } prefix = button.GetPrecedingString("Left"); string other = prefix + "Right"; if (Source.IsPressed(other)) { - if (Unpresses.Contains(button)) + if (_unpresses.Contains(button)) { return false; } @@ -132,11 +132,11 @@ namespace BizHawk.Client.Common return false; } - Unpresses.Add(other); + _unpresses.Add(other); } else { - Unpresses.Remove(button); + _unpresses.Remove(button); } } @@ -149,7 +149,7 @@ namespace BizHawk.Client.Common return Source.GetFloat(name); } - private readonly HashSet Unpresses = new HashSet(); + private readonly HashSet _unpresses = new HashSet(); public IController Source { get; set; } } diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.Emu.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.Emu.cs index 6f50807953..bd7c0af0b9 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.Emu.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.Emu.cs @@ -17,25 +17,25 @@ namespace BizHawk.Client.Common public sealed class EmulatorLuaLibrary : LuaLibraryBase { [RequiredService] - public IEmulator Emulator { get; set; } + private IEmulator Emulator { get; set; } [OptionalService] - public IDebuggable DebuggableCore { get; set; } + private IDebuggable DebuggableCore { get; set; } [OptionalService] - public IDisassemblable DisassemblableCore { get; set; } + private IDisassemblable DisassemblableCore { get; set; } [OptionalService] private IMemoryDomains MemoryDomains { get; set; } [OptionalService] - public IInputPollable InputPollableCore { get; set; } + private IInputPollable InputPollableCore { get; set; } [OptionalService] - public IRegionable RegionableCore { get; set; } + private IRegionable RegionableCore { get; set; } [OptionalService] - public IBoardInfo BoardInfo { get; set; } + private IBoardInfo BoardInfo { get; set; } public Action FrameAdvanceCallback { get; set; } public Action YieldCallback { get; set; } diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.Events.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.Events.cs index ce0e1d03ea..182f578c83 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.Events.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.Events.cs @@ -14,13 +14,13 @@ namespace BizHawk.Client.Common public sealed class EventLuaLibrary : LuaLibraryBase { [OptionalService] - public IInputPollable InputPollableCore { get; set; } + private IInputPollable InputPollableCore { get; set; } [OptionalService] - public IDebuggable DebuggableCore { get; set; } + private IDebuggable DebuggableCore { get; set; } [RequiredService] - public IEmulator Emulator { get; set; } + private IEmulator Emulator { get; set; } private readonly LuaFunctionList _luaFunctions = new LuaFunctionList(); diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.GameInfo.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.GameInfo.cs index c1e2ef60ab..9fccc97c64 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.GameInfo.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.GameInfo.cs @@ -7,11 +7,8 @@ namespace BizHawk.Client.Common { public sealed class GameInfoLuaLibrary : LuaLibraryBase { - [RequiredService] - public IEmulator Emulator { get; set; } - [OptionalService] - public IBoardInfo BoardInfo { get; set; } + private IBoardInfo BoardInfo { get; set; } public GameInfoLuaLibrary(Lua lua) : base(lua) { } diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.MemorySavestate.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.MemorySavestate.cs index cb4ca5725e..f99d06312d 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.MemorySavestate.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.MemorySavestate.cs @@ -18,19 +18,19 @@ namespace BizHawk.Client.Common public override string Name => "memorysavestate"; - private readonly Dictionary MemorySavestates = new Dictionary(); - [RequiredService] - private IStatable _statableCore { get; set; } + private IStatable StatableCore { get; set; } + + private readonly Dictionary _memorySavestates = new Dictionary(); [LuaMethodAttributes( "savecorestate", "creates a core savestate and stores it in memory. Note: a core savestate is only the raw data from the core, and not extras such as movie input logs, or framebuffers. Returns a unique identifer for the savestate")] public string SaveCoreStateToMemory() { var guid = Guid.NewGuid(); - var bytes = (byte[])_statableCore.SaveStateBinary().Clone(); + var bytes = (byte[])StatableCore.SaveStateBinary().Clone(); - MemorySavestates.Add(guid, bytes); + _memorySavestates.Add(guid, bytes); return guid.ToString(); } @@ -42,12 +42,12 @@ namespace BizHawk.Client.Common try { - var state = MemorySavestates[guid]; + var state = _memorySavestates[guid]; using (var ms = new MemoryStream(state)) using (var br = new BinaryReader(ms)) { - _statableCore.LoadStateBinary(br); + StatableCore.LoadStateBinary(br); } } catch @@ -60,13 +60,13 @@ namespace BizHawk.Client.Common public void DeleteState(string identifier) { var guid = new Guid(identifier); - MemorySavestates.Remove(guid); + _memorySavestates.Remove(guid); } [LuaMethodAttributes("clearstatesfrommemory", "clears all savestates stored in memory")] public void ClearInMemoryStates() { - MemorySavestates.Clear(); + _memorySavestates.Clear(); } } } diff --git a/BizHawk.Client.Common/lua/EmuLuaLibrary.NES.cs b/BizHawk.Client.Common/lua/EmuLuaLibrary.NES.cs index 14c49f4496..9c350eb353 100644 --- a/BizHawk.Client.Common/lua/EmuLuaLibrary.NES.cs +++ b/BizHawk.Client.Common/lua/EmuLuaLibrary.NES.cs @@ -21,17 +21,17 @@ namespace BizHawk.Client.Common : base(lua) { } [OptionalService] - private NES _neshawk { get; set; } + private NES Neshawk { get; set; } [OptionalService] - private QuickNES _quicknes { get; set; } + private QuickNES Quicknes { get; set; } [OptionalService] - private IMemoryDomains _memoryDomains { get; set; } + private IMemoryDomains MemoryDomains { get; set; } - private bool NESAvailable => _neshawk != null || _quicknes != null; + private bool NESAvailable => Neshawk != null || Quicknes != null; - private bool HasMemoryDOmains => _memoryDomains != null; + private bool HasMemoryDOmains => MemoryDomains != null; public NesLuaLibrary(Lua lua, Action logOutputCallback) : base(lua, logOutputCallback) { } @@ -46,7 +46,7 @@ namespace BizHawk.Client.Common { var decoder = new NESGameGenieDecoder(code); var watch = Watch.GenerateWatch( - _memoryDomains["System Bus"], + MemoryDomains["System Bus"], decoder.Address, WatchSize.Byte, DisplayType.Hex, @@ -64,14 +64,14 @@ namespace BizHawk.Client.Common "getallowmorethaneightsprites", "Gets the NES setting 'Allow more than 8 sprites per scanline' value")] public bool GetAllowMoreThanEightSprites() { - if (_quicknes != null) + if (Quicknes != null) { - return _quicknes.GetSettings().NumSprites != 8; + return Quicknes.GetSettings().NumSprites != 8; } - if (_neshawk != null) + if (Neshawk != null) { - return _neshawk.GetSettings().AllowMoreThanEightSprites; + return Neshawk.GetSettings().AllowMoreThanEightSprites; } throw new InvalidOperationException(); @@ -81,16 +81,16 @@ namespace BizHawk.Client.Common "getbottomscanline", "Gets the current value for the bottom scanline value")] public int GetBottomScanline(bool pal = false) { - if (_quicknes != null) + if (Quicknes != null) { - return _quicknes.GetSettings().ClipTopAndBottom ? 231 : 239; + return Quicknes.GetSettings().ClipTopAndBottom ? 231 : 239; } - if (_neshawk != null) + if (Neshawk != null) { return pal - ? _neshawk.GetSettings().PAL_BottomLine - : _neshawk.GetSettings().NTSC_BottomLine; + ? Neshawk.GetSettings().PAL_BottomLine + : Neshawk.GetSettings().NTSC_BottomLine; } throw new InvalidOperationException(); @@ -100,14 +100,14 @@ namespace BizHawk.Client.Common "getclipleftandright", "Gets the current value for the Clip Left and Right sides option")] public bool GetClipLeftAndRight() { - if (_quicknes != null) + if (Quicknes != null) { - return _quicknes.GetSettings().ClipLeftAndRight; + return Quicknes.GetSettings().ClipLeftAndRight; } - if (_neshawk != null) + if (Neshawk != null) { - return _neshawk.GetSettings().ClipLeftAndRight; + return Neshawk.GetSettings().ClipLeftAndRight; } throw new InvalidOperationException(); @@ -117,14 +117,14 @@ namespace BizHawk.Client.Common "getdispbackground", "Indicates whether or not the bg layer is being displayed")] public bool GetDisplayBackground() { - if (_quicknes != null) + if (Quicknes != null) { return true; } - if (_neshawk != null) + if (Neshawk != null) { - return _neshawk.GetSettings().DispBackground; + return Neshawk.GetSettings().DispBackground; } throw new InvalidOperationException(); @@ -134,14 +134,14 @@ namespace BizHawk.Client.Common "getdispsprites", "Indicates whether or not sprites are being displayed")] public bool GetDisplaySprites() { - if (_quicknes != null) + if (Quicknes != null) { - return _quicknes.GetSettings().NumSprites > 0; + return Quicknes.GetSettings().NumSprites > 0; } - if (_neshawk != null) + if (Neshawk != null) { - return _neshawk.GetSettings().DispSprites; + return Neshawk.GetSettings().DispSprites; } throw new InvalidOperationException(); @@ -151,16 +151,16 @@ namespace BizHawk.Client.Common "gettopscanline", "Gets the current value for the top scanline value")] public int GetTopScanline(bool pal = false) { - if (_quicknes != null) + if (Quicknes != null) { - return _quicknes.GetSettings().ClipTopAndBottom ? 8 : 0; + return Quicknes.GetSettings().ClipTopAndBottom ? 8 : 0; } - if (_neshawk != null) + if (Neshawk != null) { return pal - ? _neshawk.GetSettings().PAL_TopLine - : _neshawk.GetSettings().NTSC_TopLine; + ? Neshawk.GetSettings().PAL_TopLine + : Neshawk.GetSettings().NTSC_TopLine; } throw new InvalidOperationException(); @@ -182,17 +182,17 @@ namespace BizHawk.Client.Common "setallowmorethaneightsprites", "Sets the NES setting 'Allow more than 8 sprites per scanline'")] public void SetAllowMoreThanEightSprites(bool allow) { - if (_neshawk != null) + if (Neshawk != null) { - var s = _neshawk.GetSettings(); + var s = Neshawk.GetSettings(); s.AllowMoreThanEightSprites = allow; - _neshawk.PutSettings(s); + Neshawk.PutSettings(s); } - else if (_quicknes != null) + else if (Quicknes != null) { - var s = _quicknes.GetSettings(); + var s = Quicknes.GetSettings(); s.NumSprites = allow ? 64 : 8; - _quicknes.PutSettings(s); + Quicknes.PutSettings(s); } } @@ -200,17 +200,17 @@ namespace BizHawk.Client.Common "setclipleftandright", "Sets the Clip Left and Right sides option")] public void SetClipLeftAndRight(bool leftandright) { - if (_neshawk != null) + if (Neshawk != null) { - var s = _neshawk.GetSettings(); + var s = Neshawk.GetSettings(); s.ClipLeftAndRight = leftandright; - _neshawk.PutSettings(s); + Neshawk.PutSettings(s); } - else if (_quicknes != null) + else if (Quicknes != null) { - var s = _quicknes.GetSettings(); + var s = Quicknes.GetSettings(); s.ClipLeftAndRight = leftandright; - _quicknes.PutSettings(s); + Quicknes.PutSettings(s); } } @@ -218,11 +218,11 @@ namespace BizHawk.Client.Common "setdispbackground", "Sets whether or not the background layer will be displayed")] public void SetDisplayBackground(bool show) { - if (_neshawk != null) + if (Neshawk != null) { - var s = _neshawk.GetSettings(); + var s = Neshawk.GetSettings(); s.DispBackground = show; - _neshawk.PutSettings(s); + Neshawk.PutSettings(s); } } @@ -230,17 +230,17 @@ namespace BizHawk.Client.Common "setdispsprites", "Sets whether or not sprites will be displayed")] public void SetDisplaySprites(bool show) { - if (_neshawk != null) + if (Neshawk != null) { - var s = _neshawk.GetSettings(); + var s = Neshawk.GetSettings(); s.DispSprites = show; - _neshawk.PutSettings(s); + Neshawk.PutSettings(s); } - else if (_quicknes != null) + else if (Quicknes != null) { - var s = _quicknes.GetSettings(); + var s = Quicknes.GetSettings(); s.NumSprites = show ? 8 : 0; - _quicknes.PutSettings(s); + Quicknes.PutSettings(s); } } @@ -248,7 +248,7 @@ namespace BizHawk.Client.Common "setscanlines", "sets the top and bottom scanlines to be drawn (same values as in the graphics options dialog). Top must be in the range of 0 to 127, bottom must be between 128 and 239. Not supported in the Quick Nes core")] public void SetScanlines(int top, int bottom, bool pal = false) { - if (_neshawk != null) + if (Neshawk != null) { if (top > 127) { @@ -268,7 +268,7 @@ namespace BizHawk.Client.Common bottom = 128; } - var s = _neshawk.GetSettings(); + var s = Neshawk.GetSettings(); if (pal) { @@ -281,7 +281,7 @@ namespace BizHawk.Client.Common s.NTSC_BottomLine = bottom; } - _neshawk.PutSettings(s); + Neshawk.PutSettings(s); } } } diff --git a/BizHawk.Client.Common/lua/LuaDocumentation.cs b/BizHawk.Client.Common/lua/LuaDocumentation.cs index de5c224157..f12707fbfc 100644 --- a/BizHawk.Client.Common/lua/LuaDocumentation.cs +++ b/BizHawk.Client.Common/lua/LuaDocumentation.cs @@ -82,7 +82,7 @@ __Types and notation__ public string Scope { get; set; } [JsonProperty(PropertyName = "completions")] - public List Completions = new List(); + public List Completions { get; set; } = new List(); public class Completion { diff --git a/BizHawk.Client.Common/lua/LuaMemoryBase.cs b/BizHawk.Client.Common/lua/LuaMemoryBase.cs index f763bb7044..20831ee5d2 100644 --- a/BizHawk.Client.Common/lua/LuaMemoryBase.cs +++ b/BizHawk.Client.Common/lua/LuaMemoryBase.cs @@ -16,10 +16,10 @@ namespace BizHawk.Client.Common [OptionalService] protected IMemoryDomains MemoryDomainCore { get; set; } - public LuaMemoryBase(Lua lua) + protected LuaMemoryBase(Lua lua) : base(lua) { } - public LuaMemoryBase(Lua lua, Action logOutputCallback) + protected LuaMemoryBase(Lua lua, Action logOutputCallback) : base(lua, logOutputCallback) { } protected abstract MemoryDomain Domain { get; } diff --git a/BizHawk.Client.Common/movie/MovieSession.cs b/BizHawk.Client.Common/movie/MovieSession.cs index 6d76a8e5ef..f696c4d66d 100644 --- a/BizHawk.Client.Common/movie/MovieSession.cs +++ b/BizHawk.Client.Common/movie/MovieSession.cs @@ -7,6 +7,8 @@ using BizHawk.Emulation.Cores.Nintendo.NES; using BizHawk.Emulation.Cores.Nintendo.SNES9X; using BizHawk.Emulation.Cores.Nintendo.SNES; using BizHawk.Emulation.Cores.Nintendo.GBA; +using BizHawk.Emulation.Cores.Atari.A7800Hawk; +using BizHawk.Emulation.Cores.Atari.Atari7800; namespace BizHawk.Client.Common { @@ -40,12 +42,14 @@ namespace BizHawk.Client.Common public Func AskYesNoCallback { get; set; } /// - /// Required + /// Gets or sets a callback that allows the movie session to pause the emulator + /// This is Required! /// public Action PauseCallback { get; set; } /// - /// Required + /// Gets or sets a callback that is invoked when the movie mode has changed + /// This is Required! /// public Action ModeChangedCallback { get; set; } @@ -96,7 +100,7 @@ namespace BizHawk.Client.Common MessageCallback?.Invoke(message); } - private void LatchMultitrackPlayerInput(IController playerSource, MultitrackRewiringControllerAdapter rewiredSource) + private void LatchMultitrackPlayerInput(MultitrackRewiringControllerAdapter rewiredSource) { if (MultiTrack.IsActive) { @@ -297,7 +301,7 @@ namespace BizHawk.Client.Common { if (MultiTrack.IsActive) { - LatchMultitrackPlayerInput(Global.MovieInputSourceAdapter, Global.MultitrackRewiringAdapter); + LatchMultitrackPlayerInput(Global.MultitrackRewiringAdapter); } else { @@ -461,6 +465,7 @@ namespace BizHawk.Client.Common public bool? PreviousNES_InQuickNES { get; set; } public bool? PreviousSNES_InSnes9x { get; set; } public bool? PreviousGBA_UsemGBA { get; set; } + public bool? PreviousA78_UseEmu7800 { get; set; } public void QueueNewMovie(IMovie movie, bool record, IEmulator emulator) { @@ -475,13 +480,6 @@ namespace BizHawk.Client.Common } } - // TODO: Delete this, this save is utterly useless. - // Movie was saved immediately before calling QueeuNewMovie. (StartNewMovie) - ////if (Movie.IsActive && !string.IsNullOrEmpty(Movie.Filename)) - ////{ - //// Movie.Save(); - ////} - // Note: this populates MovieControllerAdapter's Type with the approparite controller // Don't set it to a movie instance of the adapter or you will lose the definition! InputManager.RewireInputChain(); @@ -513,7 +511,7 @@ namespace BizHawk.Client.Common PreviousSNES_InSnes9x = Global.Config.SNES_InSnes9x; Global.Config.SNES_InSnes9x = true; } - else + else if (movie.Core == bsnesName) { PreviousSNES_InSnes9x = Global.Config.SNES_InSnes9x; Global.Config.SNES_InSnes9x = false; @@ -529,12 +527,28 @@ namespace BizHawk.Client.Common PreviousGBA_UsemGBA = Global.Config.GBA_UsemGBA; Global.Config.GBA_UsemGBA = true; } - else + else if (movie.Core == vbaNextName) { - PreviousSNES_InSnes9x = Global.Config.GBA_UsemGBA; + PreviousGBA_UsemGBA = Global.Config.GBA_UsemGBA; Global.Config.GBA_UsemGBA = false; } } + else if (!record && emulator.SystemId == "A78") // meh, copy pasta one more time, last time, I promise + { + var atari7800HawkName = ((CoreAttributes)Attribute.GetCustomAttribute(typeof(A7800Hawk), typeof(CoreAttributes))).CoreName; + var emu7800HawkName = ((CoreAttributes)Attribute.GetCustomAttribute(typeof(Atari7800), typeof(CoreAttributes))).CoreName; + + if (movie.Core == atari7800HawkName) + { + PreviousA78_UseEmu7800 = Global.Config.A78_UseEmu7800; + Global.Config.A78_UseEmu7800 = true; + } + else if (movie.Core == emu7800HawkName) + { + PreviousA78_UseEmu7800 = Global.Config.A78_UseEmu7800; + Global.Config.A78_UseEmu7800 = false; + } + } if (record) // This is a hack really, we need to set the movie to its propert state so that it will be considered active later { diff --git a/BizHawk.Client.Common/movie/Subtitle.cs b/BizHawk.Client.Common/movie/Subtitle.cs index f7bab1ad1d..b59be8679f 100644 --- a/BizHawk.Client.Common/movie/Subtitle.cs +++ b/BizHawk.Client.Common/movie/Subtitle.cs @@ -83,7 +83,7 @@ namespace BizHawk.Client.Common // Color tag open if (addcolortag) { - uint rgb = (Color & 0x00FFFFFF); + uint rgb = Color & 0x00FFFFFF; sb.Append(""); diff --git a/BizHawk.Client.Common/movie/bk2/Bk2FloatConstants.cs b/BizHawk.Client.Common/movie/bk2/Bk2FloatConstants.cs index 2d024f7eda..6851f27823 100644 --- a/BizHawk.Client.Common/movie/bk2/Bk2FloatConstants.cs +++ b/BizHawk.Client.Common/movie/bk2/Bk2FloatConstants.cs @@ -15,49 +15,46 @@ namespace BizHawk.Client.Common .Replace("P4 ", "") .Replace("Key ", ""); - if (SystemOverrides.ContainsKey(Global.Emulator.SystemId) && SystemOverrides[Global.Emulator.SystemId].ContainsKey(key)) + if (_systemOverrides.ContainsKey(Global.Emulator.SystemId) && _systemOverrides[Global.Emulator.SystemId].ContainsKey(key)) { - return SystemOverrides[Global.Emulator.SystemId][key]; + return _systemOverrides[Global.Emulator.SystemId][key]; } - if (BaseMnemonicLookupTable.ContainsKey(key)) + if (_baseMnemonicLookupTable.ContainsKey(key)) { - return BaseMnemonicLookupTable[key]; + return _baseMnemonicLookupTable[key]; } return button; } } - private readonly Dictionary BaseMnemonicLookupTable = new Dictionary + private readonly Dictionary _baseMnemonicLookupTable = new Dictionary { - { "Zapper X", "zapX" }, - { "Zapper Y", "zapY" }, - { "Paddle", "Pad" }, - { "Pen", "Pen" }, - { "Mouse X", "mX" }, - { "Mouse Y", "mY" }, - { "Lightgun X", "lX" }, - { "Lightgun Y", "lY" }, - { "X Axis", "aX" }, - { "Y Axis", "aY" }, - { "LStick X", "lsX" }, - { "LStick Y", "lsY" }, - { "RStick X", "rsX" }, - { "RStick Y", "rsY" }, - { "Disc Select", "Disc" } + ["Zapper X"] = "zapX", + ["Zapper Y"] = "zapY", + ["Paddle"] = "Pad", + ["Pen"] = "Pen", + ["Mouse X"] = "mX", + ["Mouse Y"] = "mY", + ["Lightgun X"] = "lX", + ["Lightgun Y"] = "lY", + ["X Axis"] = "aX", + ["Y Axis"] = "aY", + ["LStick X"] = "lsX", + ["LStick Y"] = "lsY", + ["RStick X"] = "rsX", + ["RStick Y"] = "rsY", + ["Disc Select"] = "Disc" }; - private readonly Dictionary> SystemOverrides = new Dictionary> + private readonly Dictionary> _systemOverrides = new Dictionary> { + ["A78"] = new Dictionary { - "A78", - new Dictionary - { - { "VPos", "X" }, - { "HPos", "Y" } - } - }, + ["VPos"] = "X", + ["HPos"] = "Y" + } }; } } diff --git a/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs b/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs index 8ce9e4b093..1df809e86b 100644 --- a/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs +++ b/BizHawk.Client.Common/movie/bk2/Bk2LogEntryGenerator.cs @@ -8,8 +8,8 @@ namespace BizHawk.Client.Common { public class Bk2LogEntryGenerator : ILogEntryGenerator { - private readonly Bk2MnemonicConstants Mnemonics = new Bk2MnemonicConstants(); - private readonly Bk2FloatConstants FloatLookup = new Bk2FloatConstants(); + private readonly Bk2MnemonicConstants _mnemonics = new Bk2MnemonicConstants(); + private readonly Bk2FloatConstants _floatLookup = new Bk2FloatConstants(); private readonly string _logKey; private IController _source; @@ -72,11 +72,11 @@ namespace BizHawk.Client.Common { if (_source.Definition.BoolButtons.Contains(button)) { - dict.Add(button, Mnemonics[button].ToString()); + dict.Add(button, _mnemonics[button].ToString()); } else if (_source.Definition.FloatControls.Contains(button)) { - dict.Add(button, FloatLookup[button]); + dict.Add(button, _floatLookup[button]); } } } @@ -131,7 +131,7 @@ namespace BizHawk.Client.Common } else { - sb.Append(_source.IsPressed(button) ? Mnemonics[button] : forInputDisplay ? ' ' : '.'); + sb.Append(_source.IsPressed(button) ? _mnemonics[button] : forInputDisplay ? ' ' : '.'); } } } diff --git a/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs b/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs index d39dd7b42d..59fa396131 100644 --- a/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs +++ b/BizHawk.Client.Common/movie/bk2/Bk2Movie.IO.cs @@ -178,7 +178,7 @@ namespace BizHawk.Client.Common bs.PutLump(BinaryStateLump.Subtitles, tw => tw.WriteLine(Subtitles.ToString())); bs.PutLump(BinaryStateLump.SyncSettings, tw => tw.WriteLine(_syncSettingsJson)); - bs.PutLump(BinaryStateLump.Input, tw => WriteInputLog(tw)); + bs.PutLump(BinaryStateLump.Input, WriteInputLog); if (StartsFromSavestate) { @@ -211,7 +211,7 @@ namespace BizHawk.Client.Common protected void ClearBeforeLoad() { Header.Clear(); - _log.Clear(); + Log.Clear(); Subtitles.Clear(); Comments.Clear(); _syncSettingsJson = ""; diff --git a/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs b/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs index 700eba24ae..9d9ac17618 100644 --- a/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs +++ b/BizHawk.Client.Common/movie/bk2/Bk2Movie.InputLog.cs @@ -6,8 +6,8 @@ namespace BizHawk.Client.Common { public partial class Bk2Movie { - protected IStringLog _log; - protected string LogKey = ""; + protected IStringLog Log { get; set; } + protected string LogKey { get; set; } = ""; public void WriteInputLog(TextWriter writer) { @@ -24,13 +24,13 @@ namespace BizHawk.Client.Common if (LoopOffset.HasValue) { - if (frame < _log.Count) + if (frame < Log.Count) { getframe = frame; } else { - getframe = ((frame - LoopOffset.Value) % (_log.Count - LoopOffset.Value)) + LoopOffset.Value; + getframe = ((frame - LoopOffset.Value) % (Log.Count - LoopOffset.Value)) + LoopOffset.Value; } } else @@ -38,7 +38,7 @@ namespace BizHawk.Client.Common getframe = frame; } - return _log[getframe]; + return Log[getframe]; } return ""; @@ -52,13 +52,13 @@ namespace BizHawk.Client.Common // We are in record mode so replace the movie log with the one from the savestate if (!Global.MovieSession.MultiTrack.IsActive) { - if (Global.Config.EnableBackupMovies && MakeBackup && _log.Count != 0) + if (Global.Config.EnableBackupMovies && MakeBackup && Log.Count != 0) { SaveBackup(); MakeBackup = false; } - _log.Clear(); + Log.Clear(); while (true) { var line = reader.ReadLine(); @@ -102,7 +102,7 @@ namespace BizHawk.Client.Common } else if (line[0] == '|') { - _log.Add(line); + Log.Add(line); } } } @@ -162,21 +162,21 @@ namespace BizHawk.Client.Common var stateFramei = stateFrame ?? 0; - if (stateFramei > 0 && stateFramei < _log.Count) + if (stateFramei > 0 && stateFramei < Log.Count) { if (!Global.Config.VBAStyleMovieLoadState) { Truncate(stateFramei); } } - else if (stateFramei > _log.Count) // Post movie savestate + else if (stateFramei > Log.Count) // Post movie savestate { if (!Global.Config.VBAStyleMovieLoadState) { - Truncate(_log.Count); + Truncate(Log.Count); } - _mode = Moviemode.Finished; + Mode = Moviemode.Finished; } if (IsCountingRerecords) @@ -243,7 +243,7 @@ namespace BizHawk.Client.Common stateFrame = newLog.Count; // In case the frame count failed to parse, revert to using the entire state input log } - if (_log.Count < stateFrame) + if (Log.Count < stateFrame) { if (IsFinished) { @@ -253,14 +253,14 @@ namespace BizHawk.Client.Common errorMessage = "The savestate is from frame " + newLog.Count + " which is greater than the current movie length of " - + _log.Count; + + Log.Count; return false; } for (var i = 0; i < stateFrame; i++) { - if (_log[i] != newLog[i]) + if (Log[i] != newLog[i]) { errorMessage = "The savestate input does not match the movie input at frame " + (i + 1) @@ -272,18 +272,18 @@ namespace BizHawk.Client.Common if (stateFrame > newLog.Count) // stateFrame is greater than state input log, so movie finished mode { - if (_mode == Moviemode.Play || _mode == Moviemode.Finished) + if (Mode == Moviemode.Play || Mode == Moviemode.Finished) { - _mode = Moviemode.Finished; + Mode = Moviemode.Finished; return true; } return false; } - if (_mode == Moviemode.Finished) + if (Mode == Moviemode.Finished) { - _mode = Moviemode.Play; + Mode = Moviemode.Play; } return true; @@ -296,7 +296,7 @@ namespace BizHawk.Client.Common writer.WriteLine(lg.GenerateLogKey()); - foreach (var record in _log) + foreach (var record in Log) { writer.WriteLine(record); } diff --git a/BizHawk.Client.Common/movie/bk2/Bk2Movie.ModeApi.cs b/BizHawk.Client.Common/movie/bk2/Bk2Movie.ModeApi.cs index 3eec799f7a..84ba6b80e0 100644 --- a/BizHawk.Client.Common/movie/bk2/Bk2Movie.ModeApi.cs +++ b/BizHawk.Client.Common/movie/bk2/Bk2Movie.ModeApi.cs @@ -9,41 +9,41 @@ namespace BizHawk.Client.Common Inactive, Play, Record, Finished } - protected Moviemode _mode = Moviemode.Inactive; + protected Moviemode Mode { get; set; } = Moviemode.Inactive; - public bool IsActive => _mode != Moviemode.Inactive; + public bool IsActive => Mode != Moviemode.Inactive; - public bool IsPlaying => _mode == Moviemode.Play || _mode == Moviemode.Finished; + public bool IsPlaying => Mode == Moviemode.Play || Mode == Moviemode.Finished; - public bool IsRecording => _mode == Moviemode.Record; + public bool IsRecording => Mode == Moviemode.Record; - public bool IsFinished => _mode == Moviemode.Finished; + public bool IsFinished => Mode == Moviemode.Finished; public virtual void StartNewRecording() { - _mode = Moviemode.Record; - if (Global.Config.EnableBackupMovies && MakeBackup && _log.Any()) + Mode = Moviemode.Record; + if (Global.Config.EnableBackupMovies && MakeBackup && Log.Any()) { SaveBackup(); MakeBackup = false; } - _log.Clear(); + Log.Clear(); } public virtual void StartNewPlayback() { - _mode = Moviemode.Play; + Mode = Moviemode.Play; } public virtual void SwitchToRecord() { - _mode = Moviemode.Record; + Mode = Moviemode.Record; } public virtual void SwitchToPlay() { - _mode = Moviemode.Play; + Mode = Moviemode.Play; } public virtual bool Stop(bool saveChanges = true) @@ -51,7 +51,7 @@ namespace BizHawk.Client.Common bool saved = false; if (saveChanges) { - if (_mode == Moviemode.Record || (IsActive && Changes)) + if (Mode == Moviemode.Record || (IsActive && Changes)) { Save(); saved = true; @@ -59,14 +59,14 @@ namespace BizHawk.Client.Common } Changes = false; - _mode = Moviemode.Inactive; + Mode = Moviemode.Inactive; return saved; } public void FinishedMode() { - _mode = Moviemode.Finished; + Mode = Moviemode.Finished; } } } diff --git a/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs b/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs index d3f3e34e2e..a7bf3f088d 100644 --- a/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs +++ b/BizHawk.Client.Common/movie/bk2/Bk2Movie.cs @@ -6,8 +6,6 @@ namespace BizHawk.Client.Common { public partial class Bk2Movie : IMovie { - protected bool MakeBackup = true; - public Bk2Movie(string filename) : this() { @@ -22,14 +20,16 @@ namespace BizHawk.Client.Common Filename = ""; IsCountingRerecords = true; - _mode = Moviemode.Inactive; + Mode = Moviemode.Inactive; MakeBackup = true; Header[HeaderKeys.MOVIEVERSION] = "BizHawk v2.0.0"; - _log = StringLogUtil.MakeStringLog(); + Log = StringLogUtil.MakeStringLog(); } + protected bool MakeBackup { get; set; } + private string _filename; public string Filename @@ -70,11 +70,11 @@ namespace BizHawk.Client.Common return double.PositiveInfinity; } - return _log.Count; + return Log.Count; } } - public int InputLogLength => _log.Count; + public int InputLogLength => Log.Count; #region Log Editing @@ -82,7 +82,7 @@ namespace BizHawk.Client.Common { var lg = LogGeneratorInstance(); lg.SetSource(source); - _log.Add(lg.GenerateLogEntry()); + Log.Add(lg.GenerateLogEntry()); Changes = true; } @@ -90,7 +90,7 @@ namespace BizHawk.Client.Common { if (Global.Config.VBAStyleMovieLoadState) { - if (Global.Emulator.Frame < _log.Count) + if (Global.Emulator.Frame < Log.Count) { Truncate(Global.Emulator.Frame); } @@ -109,9 +109,9 @@ namespace BizHawk.Client.Common // and it is weird for Truncate to possibly not truncate if (!Global.MovieSession.MultiTrack.IsActive) { - if (frame < _log.Count) + if (frame < Log.Count) { - _log.RemoveRange(frame, _log.Count - frame); + Log.RemoveRange(frame, Log.Count - frame); Changes = true; } } @@ -125,13 +125,13 @@ namespace BizHawk.Client.Common if (LoopOffset.HasValue) { - if (frame < _log.Count) + if (frame < Log.Count) { getframe = frame; } else { - getframe = ((frame - LoopOffset.Value) % (_log.Count - LoopOffset.Value)) + LoopOffset.Value; + getframe = ((frame - LoopOffset.Value) % (Log.Count - LoopOffset.Value)) + LoopOffset.Value; } } else @@ -144,7 +144,7 @@ namespace BizHawk.Client.Common Definition = Global.MovieSession.MovieControllerAdapter.Definition }; - adapter.SetControllersAsMnemonic(_log[getframe]); + adapter.SetControllersAsMnemonic(Log[getframe]); return adapter; } @@ -172,13 +172,13 @@ namespace BizHawk.Client.Common protected void SetFrameAt(int frameNum, string frame) { - if (_log.Count > frameNum) + if (Log.Count > frameNum) { - _log[frameNum] = frame; + Log[frameNum] = frame; } else { - _log.Add(frame); + Log.Add(frame); } } } diff --git a/BizHawk.Client.Common/movie/bk2/StringLogs.cs b/BizHawk.Client.Common/movie/bk2/StringLogs.cs index 1f7b6f320c..f2893dc43c 100644 --- a/BizHawk.Client.Common/movie/bk2/StringLogs.cs +++ b/BizHawk.Client.Common/movie/bk2/StringLogs.cs @@ -8,8 +8,8 @@ namespace BizHawk.Client.Common { public static class StringLogUtil { - public static bool DefaultToDisk; - public static bool DefaultToAWE; + public static bool DefaultToDisk { get; set; } + public static bool DefaultToAWE { get; set; } public static IStringLog MakeStringLog() { if (DefaultToDisk) @@ -55,23 +55,24 @@ namespace BizHawk.Client.Common } /// - /// A dumb-ish IStringLog with storage on disk with no provision for recovering lost space, except upon Clear() - /// The purpose here is to avoid having too complicated buggy logic or a dependency on sqlite or such. + /// A dumb IStringLog with storage on disk with no provision for recovering lost space, except upon Clear() + /// The purpose here is to avoid having too complicated buggy logic or a dependency on SQLite or such. /// It should be faster than those alternatives, but wasteful of disk space. /// It should also be easier to add new IList<string>-like methods than dealing with a database /// internal class StreamStringLog : IStringLog { - List Offsets = new List(); - long cursor = 0; - BinaryWriter bw; - BinaryReader br; - bool mDisk; + private readonly Stream stream; + private readonly List _offsets = new List(); + private readonly BinaryWriter _bw; + private readonly BinaryReader _br; + private readonly bool _mDisk; + + private long _cursor; - Stream stream; public StreamStringLog(bool disk) { - mDisk = disk; + _mDisk = disk; if (disk) { var path = TempFileCleaner.GetTempFilename("movieOnDisk"); @@ -82,13 +83,13 @@ namespace BizHawk.Client.Common stream = new AWEMemoryStream(); } - bw = new BinaryWriter(stream); - br = new BinaryReader(stream); + _bw = new BinaryWriter(stream); + _br = new BinaryReader(stream); } public IStringLog Clone() { - StreamStringLog ret = new StreamStringLog(mDisk); // doesnt necessarily make sense to copy the mDisk value, they could be designated for different targets... + StreamStringLog ret = new StreamStringLog(_mDisk); // doesnt necessarily make sense to copy the mDisk value, they could be designated for different targets... for (int i = 0; i < Count; i++) { ret.Add(this[i]); @@ -102,52 +103,52 @@ namespace BizHawk.Client.Common stream.Dispose(); } - public int Count => Offsets.Count; + public int Count => _offsets.Count; public void Clear() { stream.SetLength(0); - Offsets.Clear(); - cursor = 0; + _offsets.Clear(); + _cursor = 0; } public void Add(string str) { stream.Position = stream.Length; - Offsets.Add(stream.Position); - bw.Write(str); - bw.Flush(); + _offsets.Add(stream.Position); + _bw.Write(str); + _bw.Flush(); } public void RemoveAt(int index) { // no garbage collection in the disk file... oh well. - Offsets.RemoveAt(index); + _offsets.RemoveAt(index); } public string this[int index] { get { - stream.Position = Offsets[index]; - return br.ReadString(); + stream.Position = _offsets[index]; + return _br.ReadString(); } set { stream.Position = stream.Length; - Offsets[index] = stream.Position; - bw.Write(value); - bw.Flush(); + _offsets[index] = stream.Position; + _bw.Write(value); + _bw.Flush(); } } public void Insert(int index, string val) { stream.Position = stream.Length; - Offsets.Insert(index, stream.Position); - bw.Write(val); - bw.Flush(); + _offsets.Insert(index, stream.Position); + _bw.Write(val); + _bw.Flush(); } public void InsertRange(int index, IEnumerable collection) @@ -168,35 +169,37 @@ namespace BizHawk.Client.Common private class Enumerator : IEnumerator { - public StreamStringLog log; - int index = -1; - public string Current { get { return log[index]; } } - object System.Collections.IEnumerator.Current { get { return log[index]; } } + public StreamStringLog Log { get; set; } + private int _index = -1; + + public string Current => Log[_index]; + object System.Collections.IEnumerator.Current => Log[_index]; + bool System.Collections.IEnumerator.MoveNext() { - index++; - if (index >= log.Count) + _index++; + if (_index >= Log.Count) { - index = log.Count; + _index = Log.Count; return false; } return true; } - void System.Collections.IEnumerator.Reset() { index = -1; } + void System.Collections.IEnumerator.Reset() { _index = -1; } public void Dispose() { } } IEnumerator IEnumerable.GetEnumerator() { - return new Enumerator { log = this }; + return new Enumerator { Log = this }; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { - return new Enumerator { log = this }; + return new Enumerator { Log = this }; } public void RemoveRange(int index, int count) diff --git a/BizHawk.Client.Common/movie/bkm/BkmControllerAdapter.cs b/BizHawk.Client.Common/movie/bkm/BkmControllerAdapter.cs index 2279ac91f8..5e44bdcd56 100644 --- a/BizHawk.Client.Common/movie/bkm/BkmControllerAdapter.cs +++ b/BizHawk.Client.Common/movie/bkm/BkmControllerAdapter.cs @@ -487,7 +487,7 @@ namespace BizHawk.Client.Common for (int player = 1; player <= BkmMnemonicConstants.Players[ControlType]; player++) { - int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + BkmMnemonicConstants.Analogs[ControlType].Count * 4 + 1 + 1); + int srcindex = (player - 1) * (BkmMnemonicConstants.Buttons[ControlType].Count + (BkmMnemonicConstants.Analogs[ControlType].Count * 4) + 1 + 1); if (mnemonic.Length < srcindex + 3 + BkmMnemonicConstants.Buttons[ControlType].Count - 1) { diff --git a/BizHawk.Client.Common/movie/import/Fm2Import.cs b/BizHawk.Client.Common/movie/import/Fm2Import.cs index a822f65c1d..194f7ce244 100644 --- a/BizHawk.Client.Common/movie/import/Fm2Import.cs +++ b/BizHawk.Client.Common/movie/import/Fm2Import.cs @@ -45,7 +45,7 @@ namespace BizHawk.Client.Common } else if (line.ToLower().StartsWith("emuversion")) { - Result.Movie.Comments.Add($"{EMULATIONORIGIN} {emulator} version {ParseHeader(line, "emuVersion")}"); + Result.Movie.Comments.Add($"{Emulationorigin} {emulator} version {ParseHeader(line, "emuVersion")}"); } else if (line.ToLower().StartsWith("version")) { @@ -57,7 +57,7 @@ namespace BizHawk.Client.Common } else { - Result.Movie.Comments.Add(MOVIEORIGIN + " .fm2 version 3"); + Result.Movie.Comments.Add(Movieorigin + " .fm2 version 3"); } } else if (line.ToLower().StartsWith("romfilename")) diff --git a/BizHawk.Client.Common/movie/import/IMovieImport.cs b/BizHawk.Client.Common/movie/import/IMovieImport.cs index 9b5551c248..3f3f0bfafb 100644 --- a/BizHawk.Client.Common/movie/import/IMovieImport.cs +++ b/BizHawk.Client.Common/movie/import/IMovieImport.cs @@ -11,25 +11,25 @@ namespace BizHawk.Client.Common public abstract class MovieImporter : IMovieImport { - public const string COMMENT = "comment"; - public const string COREORIGIN = "CoreOrigin"; + public const string Comment = "comment"; + public const string Coreorigin = "CoreOrigin"; public const string CRC16 = "CRC16"; public const string CRC32 = "CRC32"; - public const string EMULATIONORIGIN = "emuOrigin"; - public const string GAMECODE = "GameCode"; - public const string INTERNALCHECKSUM = "InternalChecksum"; - public const string JAPAN = "Japan"; - public const string MD5 = "MD5"; - public const string MOVIEORIGIN = "MovieOrigin"; - public const string PORT1 = "port1"; - public const string PORT2 = "port2"; - public const string PROJECTID = "ProjectID"; + protected const string Emulationorigin = "emuOrigin"; + public const string Gamecode = "GameCode"; + public const string InternalChecksum = "InternalChecksum"; + public const string Japan = "Japan"; + protected const string MD5 = "MD5"; + protected const string Movieorigin = "MovieOrigin"; + public const string Port1 = "port1"; + public const string Port2 = "port2"; + public const string ProjectId = "ProjectID"; public const string SHA256 = "SHA256"; - public const string SUPERGAMEBOYMODE = "SuperGameBoyMode"; - public const string STARTSECOND = "StartSecond"; - public const string STARTSUBSECOND = "StartSubSecond"; - public const string SYNCHACK = "SyncHack"; - public const string UNITCODE = "UnitCode"; + public const string SuperGameboyMode = "SuperGameBoyMode"; + public const string StartSecond = "StartSecond"; + public const string StartSubSecond = "StartSubSecond"; + public const string SyncHack = "SyncHack"; + public const string UnitCode = "UnitCode"; public ImportResult Import(string path) { @@ -49,9 +49,9 @@ namespace BizHawk.Client.Common return Result; } - protected ImportResult Result = new ImportResult(); + protected ImportResult Result { get; } = new ImportResult(); - protected FileInfo SourceFile; + protected FileInfo SourceFile { get; private set; } protected abstract void RunImport(); diff --git a/BizHawk.Client.Common/movie/import/PJMImport.cs b/BizHawk.Client.Common/movie/import/PJMImport.cs index 3527d84b88..6c997698cc 100644 --- a/BizHawk.Client.Common/movie/import/PJMImport.cs +++ b/BizHawk.Client.Common/movie/import/PJMImport.cs @@ -22,9 +22,9 @@ namespace BizHawk.Client.Common { var info = ParseHeader(movie, "PJM ", br); - fs.Seek(info.controllerDataOffset, SeekOrigin.Begin); + fs.Seek(info.ControllerDataOffset, SeekOrigin.Begin); - if (info.binaryFormat) + if (info.BinaryFormat) { ParseBinaryInputLog(br, movie, info); } @@ -87,7 +87,7 @@ namespace BizHawk.Client.Common if ((flags & 0x40) != 0) { - info.binaryFormat = false; + info.BinaryFormat = false; } if ((flags & 0x80) != 0 || (flags2 & 0x01) != 0) @@ -103,13 +103,13 @@ namespace BizHawk.Client.Common // to mean no controller present. case 0: case 8: - info.player1Type = OctoshockDll.ePeripheralType.None; + info.Player1Type = OctoshockDll.ePeripheralType.None; break; case 4: - info.player1Type = OctoshockDll.ePeripheralType.Pad; + info.Player1Type = OctoshockDll.ePeripheralType.Pad; break; case 7: - info.player1Type = OctoshockDll.ePeripheralType.DualShock; + info.Player1Type = OctoshockDll.ePeripheralType.DualShock; break; default: Result.Errors.Add("Movie has unrecognised controller type for Player 1."); @@ -121,13 +121,13 @@ namespace BizHawk.Client.Common { case 0: case 8: - info.player1Type = OctoshockDll.ePeripheralType.None; + info.Player1Type = OctoshockDll.ePeripheralType.None; break; case 4: - info.player1Type = OctoshockDll.ePeripheralType.Pad; + info.Player1Type = OctoshockDll.ePeripheralType.Pad; break; case 7: - info.player1Type = OctoshockDll.ePeripheralType.DualShock; + info.Player1Type = OctoshockDll.ePeripheralType.DualShock; break; default: Result.Errors.Add("Movie has unrecognised controller type for Player 2."); @@ -140,11 +140,11 @@ namespace BizHawk.Client.Common { Devices8 = new[] { - info.player1Type, + info.Player1Type, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, - info.player2Type, + info.Player2Type, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None @@ -162,7 +162,7 @@ namespace BizHawk.Client.Common }; movie.SyncSettingsJson = JsonConvert.SerializeObject(new { o = (object)syncsettings }, jsonSettings); - info.frameCount = br.ReadUInt32(); + info.FrameCount = br.ReadUInt32(); uint rerecordCount = br.ReadUInt32(); movie.HeaderEntries[HeaderKeys.RERECORDS] = rerecordCount.ToString(); @@ -176,14 +176,14 @@ namespace BizHawk.Client.Common // so not so useful. br.ReadBytes(20); - info.controllerDataOffset = br.ReadUInt32(); + info.ControllerDataOffset = br.ReadUInt32(); uint authorNameLength = br.ReadUInt32(); char[] authorName = br.ReadChars((int)authorNameLength); movie.HeaderEntries[HeaderKeys.AUTHOR] = new string(authorName); - info.parseSuccessful = true; + info.ParseSuccessful = true; return info; } @@ -193,9 +193,9 @@ namespace BizHawk.Client.Common SimpleController controllers = new SimpleController(); settings.FIOConfig.Devices8 = new[] { - info.player1Type, + info.Player1Type, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, - info.player2Type, + info.Player2Type, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None }; controllers.Definition = Octoshock.CreateControllerDefinition(settings); @@ -209,9 +209,9 @@ namespace BizHawk.Client.Common bool isCdTrayOpen = false; int cdNumber = 1; - for (int frame = 0; frame < info.frameCount; ++frame) + for (int frame = 0; frame < info.FrameCount; ++frame) { - if (info.player1Type != OctoshockDll.ePeripheralType.None) + if (info.Player1Type != OctoshockDll.ePeripheralType.None) { ushort controllerState = br.ReadUInt16(); @@ -228,7 +228,7 @@ namespace BizHawk.Client.Common } } - if (info.player1Type == OctoshockDll.ePeripheralType.DualShock) + if (info.Player1Type == OctoshockDll.ePeripheralType.DualShock) { controllers["P1 L3"] = (controllerState & 0x2) != 0; controllers["P1 R3"] = (controllerState & 0x4) != 0; @@ -241,7 +241,7 @@ namespace BizHawk.Client.Common } } - if (info.player2Type != OctoshockDll.ePeripheralType.None) + if (info.Player2Type != OctoshockDll.ePeripheralType.None) { ushort controllerState = br.ReadUInt16(); for (int button = 0; button < buttons.Length; button++) @@ -253,7 +253,7 @@ namespace BizHawk.Client.Common } } - if (info.player2Type == OctoshockDll.ePeripheralType.DualShock) + if (info.Player2Type == OctoshockDll.ePeripheralType.DualShock) { Tuple leftX = new Tuple("P2 LStick X", (float)br.ReadByte()); Tuple leftY = new Tuple("P2 LStick Y", (float)br.ReadByte()); @@ -304,9 +304,9 @@ namespace BizHawk.Client.Common SimpleController controllers = new SimpleController(); settings.FIOConfig.Devices8 = new[] { - info.player1Type, + info.Player1Type, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, - info.player2Type, + info.Player2Type, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None, OctoshockDll.ePeripheralType.None }; controllers.Definition = Octoshock.CreateControllerDefinition(settings); @@ -320,15 +320,15 @@ namespace BizHawk.Client.Common bool isCdTrayOpen = false; int cdNumber = 1; - for (int frame = 0; frame < info.frameCount; ++frame) + for (int frame = 0; frame < info.FrameCount; ++frame) { - if (info.player1Type != OctoshockDll.ePeripheralType.None) + if (info.Player1Type != OctoshockDll.ePeripheralType.None) { // As L3 and R3 don't exist on a standard gamepad, handle them separately later. Unfortunately // due to the layout, we handle select separately too first. controllers["P1 Select"] = br.ReadChar() != '.'; - if (info.player1Type == OctoshockDll.ePeripheralType.DualShock) + if (info.Player1Type == OctoshockDll.ePeripheralType.DualShock) { controllers["P1 L3"] = br.ReadChar() != '.'; controllers["P1 R3"] = br.ReadChar() != '.'; @@ -339,7 +339,7 @@ namespace BizHawk.Client.Common controllers["P1 " + buttons[button]] = br.ReadChar() != '.'; } - if (info.player1Type == OctoshockDll.ePeripheralType.DualShock) + if (info.Player1Type == OctoshockDll.ePeripheralType.DualShock) { // The analog controls are encoded as four space-separated numbers with a leading space string leftXRaw = new string(br.ReadChars(4)).Trim(); @@ -359,13 +359,13 @@ namespace BizHawk.Client.Common // Each controller is terminated with a pipeline. br.ReadChar(); - if (info.player2Type != OctoshockDll.ePeripheralType.None) + if (info.Player2Type != OctoshockDll.ePeripheralType.None) { // As L3 and R3 don't exist on a standard gamepad, handle them separately later. Unfortunately // due to the layout, we handle select separately too first. controllers["P2 Select"] = br.ReadChar() != '.'; - if (info.player2Type == OctoshockDll.ePeripheralType.DualShock) + if (info.Player2Type == OctoshockDll.ePeripheralType.DualShock) { controllers["P2 L3"] = br.ReadChar() != '.'; controllers["P2 R3"] = br.ReadChar() != '.'; @@ -376,7 +376,7 @@ namespace BizHawk.Client.Common controllers["P2 " + buttons[button]] = br.ReadChar() != '.'; } - if (info.player2Type == OctoshockDll.ePeripheralType.DualShock) + if (info.Player2Type == OctoshockDll.ePeripheralType.DualShock) { // The analog controls are encoded as four space-separated numbers with a leading space string leftXRaw = new string(br.ReadChars(4)).Trim(); @@ -435,13 +435,12 @@ namespace BizHawk.Client.Common protected class MiscHeaderInfo { - public bool binaryFormat = true; - public uint controllerDataOffset; - public uint frameCount; - public OctoshockDll.ePeripheralType player1Type; - public OctoshockDll.ePeripheralType player2Type; - - public bool parseSuccessful = false; + public bool BinaryFormat { get; set; } = true; + public uint ControllerDataOffset { get; set; } + public uint FrameCount { get; set; } + public OctoshockDll.ePeripheralType Player1Type { get; set; } + public OctoshockDll.ePeripheralType Player2Type { get; set; } + public bool ParseSuccessful { get; set; } } } } diff --git a/BizHawk.Client.Common/movie/import/PXMImport.cs b/BizHawk.Client.Common/movie/import/PXMImport.cs index 0844e71639..4b0481ce47 100644 --- a/BizHawk.Client.Common/movie/import/PXMImport.cs +++ b/BizHawk.Client.Common/movie/import/PXMImport.cs @@ -23,9 +23,9 @@ namespace BizHawk.Client.Common.Movie.Import { var info = ParseHeader(movie, "PXM ", br); - fs.Seek(info.controllerDataOffset, SeekOrigin.Begin); + fs.Seek(info.ControllerDataOffset, SeekOrigin.Begin); - if (info.binaryFormat) + if (info.BinaryFormat) { ParseBinaryInputLog(br, movie, info); } diff --git a/BizHawk.Client.Common/movie/interfaces/IMovieSession.cs b/BizHawk.Client.Common/movie/interfaces/IMovieSession.cs index 3c8b605edc..92f3bd42d1 100644 --- a/BizHawk.Client.Common/movie/interfaces/IMovieSession.cs +++ b/BizHawk.Client.Common/movie/interfaces/IMovieSession.cs @@ -20,6 +20,7 @@ namespace BizHawk.Client.Common bool? PreviousNES_InQuickNES { get; set; } bool? PreviousSNES_InSnes9x { get; set; } bool? PreviousGBA_UsemGBA { get; set; } + bool? PreviousA78_UseEmu7800 { get; set; } void HandleMovieOnFrameLoop(); void HandleMovieAfterFrameLoop(); diff --git a/BizHawk.Client.Common/movie/tasproj/StateManagerState.cs b/BizHawk.Client.Common/movie/tasproj/StateManagerState.cs index 01574211cd..ae5255c80c 100644 --- a/BizHawk.Client.Common/movie/tasproj/StateManagerState.cs +++ b/BizHawk.Client.Common/movie/tasproj/StateManagerState.cs @@ -39,7 +39,7 @@ namespace BizHawk.Client.Common return _state; } - return _manager.ndbdatabase.FetchAll(_id.ToString()); + return _manager.NdbDatabase.FetchAll(_id.ToString()); } set @@ -80,7 +80,7 @@ namespace BizHawk.Client.Common return; } - _manager.ndbdatabase.Store(_id.ToString(), _state, 0, _state.Length); + _manager.NdbDatabase.Store(_id.ToString(), _state, 0, _state.Length); _state = null; } @@ -92,8 +92,8 @@ namespace BizHawk.Client.Common } string key = _id.ToString(); - _state = _manager.ndbdatabase.FetchAll(key); - _manager.ndbdatabase.Release(key); + _state = _manager.NdbDatabase.FetchAll(key); + _manager.NdbDatabase.Release(key); } public void Dispose() @@ -103,7 +103,7 @@ namespace BizHawk.Client.Common return; } - _manager.ndbdatabase.Release(_id.ToString()); + _manager.NdbDatabase.Release(_id.ToString()); } } } diff --git a/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs b/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs index 021649f03e..e02b10a009 100644 --- a/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs +++ b/BizHawk.Client.Common/movie/tasproj/TasLagLog.cs @@ -9,27 +9,26 @@ namespace BizHawk.Client.Common public class TasLagLog { // TODO: Change this into a regular list. - private List LagLog = new List(); - - private List WasLag = new List(); + private List _lagLog = new List(); + private List _wasLag = new List(); public bool? this[int frame] { get { - if (frame < LagLog.Count) + if (frame < _lagLog.Count) { if (frame < 0) { return null; } - return LagLog[frame]; + return _lagLog[frame]; } - if (frame == Global.Emulator.Frame && frame == LagLog.Count) + if (frame == Global.Emulator.Frame && frame == _lagLog.Count) { - // LagLog[frame] = Global.Emulator.AsInputPollable().IsLagFrame; // Note: Side effects! + ////LagLog[frame] = Global.Emulator.AsInputPollable().IsLagFrame; // Note: Side effects! return Global.Emulator.AsInputPollable().IsLagFrame; } @@ -40,7 +39,7 @@ namespace BizHawk.Client.Common { if (!value.HasValue) { - LagLog.RemoveAt(frame); + _lagLog.RemoveAt(frame); return; } @@ -49,61 +48,61 @@ namespace BizHawk.Client.Common return; // Nothing to do } - if (frame > LagLog.Count) + if (frame > _lagLog.Count) { - System.Diagnostics.Debug.Print("Lag Log error. f" + frame + ", log: " + LagLog.Count); + System.Diagnostics.Debug.Print("Lag Log error. f" + frame + ", log: " + _lagLog.Count); return; // Can this break anything? } bool wasValue; - if (frame < LagLog.Count) + if (frame < _lagLog.Count) { - wasValue = LagLog[frame]; + wasValue = _lagLog[frame]; } - else if (frame == WasLag.Count) + else if (frame == _wasLag.Count) { wasValue = value.Value; } else { - wasValue = WasLag[frame]; + wasValue = _wasLag[frame]; } - if (frame == WasLag.Count) + if (frame == _wasLag.Count) { - WasLag.Add(wasValue); + _wasLag.Add(wasValue); } else { - WasLag[frame] = wasValue; + _wasLag[frame] = wasValue; } if (frame != 0) { - WasLag[frame - 1] = LagLog[frame - 1]; + _wasLag[frame - 1] = _lagLog[frame - 1]; } - if (frame >= LagLog.Count) + if (frame >= _lagLog.Count) { - LagLog.Add(value.Value); + _lagLog.Add(value.Value); } else { - LagLog[frame] = value.Value; + _lagLog[frame] = value.Value; } } } public void Clear() { - LagLog.Clear(); + _lagLog.Clear(); } public bool RemoveFrom(int frame) { - if (LagLog.Count > frame && frame >= 0) + if (_lagLog.Count > frame && frame >= 0) { - LagLog.RemoveRange(frame + 1, LagLog.Count - frame - 1); + _lagLog.RemoveRange(frame + 1, _lagLog.Count - frame - 1); return true; } @@ -112,41 +111,41 @@ namespace BizHawk.Client.Common public void RemoveHistoryAt(int frame) { - WasLag.RemoveAt(frame); + _wasLag.RemoveAt(frame); } public void InsertHistoryAt(int frame, bool isLag) { // LagLog was invalidated when the frame was inserted - if (frame <= LagLog.Count) + if (frame <= _lagLog.Count) { - LagLog.Insert(frame, isLag); + _lagLog.Insert(frame, isLag); } - WasLag.Insert(frame, isLag); + _wasLag.Insert(frame, isLag); } public void Save(BinaryWriter bw) { bw.Write((byte)1); // New saving format. - bw.Write(LagLog.Count); - bw.Write(WasLag.Count); - for (int i = 0; i < LagLog.Count; i++) + bw.Write(_lagLog.Count); + bw.Write(_wasLag.Count); + for (int i = 0; i < _lagLog.Count; i++) { - bw.Write(LagLog[i]); - bw.Write(WasLag[i]); + bw.Write(_lagLog[i]); + bw.Write(_wasLag[i]); } - for (int i = LagLog.Count; i < WasLag.Count; i++) + for (int i = _lagLog.Count; i < _wasLag.Count; i++) { - bw.Write(WasLag[i]); + bw.Write(_wasLag[i]); } } public void Load(BinaryReader br) { - LagLog.Clear(); - WasLag.Clear(); + _lagLog.Clear(); + _wasLag.Clear(); ////if (br.BaseStream.Length > 0) ////{ BaseStream.Length does not return the expected value. int formatVersion = br.ReadByte(); @@ -157,8 +156,8 @@ namespace BizHawk.Client.Common for (int i = 0; i < length; i++) { br.ReadInt32(); - LagLog.Add(br.ReadBoolean()); - WasLag.Add(LagLog.Last()); + _lagLog.Add(br.ReadBoolean()); + _wasLag.Add(_lagLog.Last()); } } else if (formatVersion == 1) @@ -167,13 +166,13 @@ namespace BizHawk.Client.Common int lenWas = br.ReadInt32(); for (int i = 0; i < length; i++) { - LagLog.Add(br.ReadBoolean()); - WasLag.Add(br.ReadBoolean()); + _lagLog.Add(br.ReadBoolean()); + _wasLag.Add(br.ReadBoolean()); } for (int i = length; i < lenWas; i++) { - WasLag.Add(br.ReadBoolean()); + _wasLag.Add(br.ReadBoolean()); } } ////} @@ -181,14 +180,14 @@ namespace BizHawk.Client.Common public bool? History(int frame) { - if (frame < WasLag.Count) + if (frame < _wasLag.Count) { if (frame < 0) { return null; } - return WasLag[frame]; + return _wasLag[frame]; } return null; @@ -198,12 +197,12 @@ namespace BizHawk.Client.Common { get { - if (LagLog.Count == 0) + if (_lagLog.Count == 0) { return 0; } - return LagLog.Count - 1; + return _lagLog.Count - 1; } } @@ -211,21 +210,21 @@ namespace BizHawk.Client.Common { return new TasLagLog { - LagLog = LagLog.ToList(), - WasLag = WasLag.ToList() + _lagLog = _lagLog.ToList(), + _wasLag = _wasLag.ToList() }; } public void FromLagLog(TasLagLog log) { - LagLog = log.LagLog.ToList(); - WasLag = log.WasLag.ToList(); + _lagLog = log._lagLog.ToList(); + _wasLag = log._wasLag.ToList(); } public void StartFromFrame(int index) { - LagLog.RemoveRange(0, index); - WasLag.RemoveRange(0, index); + _lagLog.RemoveRange(0, index); + _wasLag.RemoveRange(0, index); } } } diff --git a/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs b/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs index 53eeba7aad..4aab52a4e2 100644 --- a/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs +++ b/BizHawk.Client.Common/movie/tasproj/TasMovie.Editing.cs @@ -38,7 +38,7 @@ namespace BizHawk.Client.Common bool endBatch = ChangeLog.BeginNewBatch("Truncate Movie: " + frame, true); ChangeLog.AddGeneralUndo(frame, InputLogLength - 1); - if (frame < _log.Count - 1) + if (frame < Log.Count - 1) { Changes = true; } @@ -91,7 +91,7 @@ namespace BizHawk.Client.Common bool endBatch = ChangeLog.BeginNewBatch("Remove Frame: " + frame, true); ChangeLog.AddGeneralUndo(frame, InputLogLength - 1); - _log.RemoveAt(frame); + Log.RemoveAt(frame); if (BindMarkersToInput) { bool wasRecording = ChangeLog.IsRecording; @@ -138,9 +138,9 @@ namespace BizHawk.Client.Common foreach (var frame in frames.OrderByDescending(f => f)) // Removing them in reverse order allows us to remove by index; { - if (frame < _log.Count) + if (frame < Log.Count) { - _log.RemoveAt(frame); + Log.RemoveAt(frame); } if (BindMarkersToInput) // TODO: This is slow, is there a better way to do it? @@ -186,7 +186,7 @@ namespace BizHawk.Client.Common for (int i = removeUpTo - 1; i >= removeStart; i--) { - _log.RemoveAt(i); + Log.RemoveAt(i); } if (BindMarkersToInput) @@ -228,7 +228,7 @@ namespace BizHawk.Client.Common bool endBatch = ChangeLog.BeginNewBatch("Insert Frame: " + frame, true); ChangeLog.AddGeneralUndo(frame, InputLogLength); - _log.Insert(frame, inputState); + Log.Insert(frame, inputState); Changes = true; InvalidateAfter(frame); @@ -261,7 +261,7 @@ namespace BizHawk.Client.Common bool endBatch = ChangeLog.BeginNewBatch("Insert Frame: " + frame, true); ChangeLog.AddGeneralUndo(frame, InputLogLength + inputLog.Count() - 1); - _log.InsertRange(frame, inputLog); + Log.InsertRange(frame, inputLog); Changes = true; InvalidateAfter(frame); @@ -311,22 +311,22 @@ namespace BizHawk.Client.Common var lg = LogGeneratorInstance(); var states = inputStates.ToList(); - if (_log.Count < states.Count + frame) + if (Log.Count < states.Count + frame) { - ExtendMovieForEdit(states.Count + frame - _log.Count); + ExtendMovieForEdit(states.Count + frame - Log.Count); } ChangeLog.AddGeneralUndo(frame, frame + inputStates.Count() - 1, "Copy Over Input: " + frame); for (int i = 0; i < states.Count; i++) { - if (_log.Count <= frame + i) + if (Log.Count <= frame + i) { break; } lg.SetSource(states[i]); - _log[frame + i] = lg.GenerateLogEntry(); + Log[frame + i] = lg.GenerateLogEntry(); } ChangeLog.EndBatch(); @@ -344,14 +344,14 @@ namespace BizHawk.Client.Common var lg = LogGeneratorInstance(); lg.SetSource(Global.MovieSession.MovieControllerInstance()); - if (frame > _log.Count()) + if (frame > Log.Count()) { - frame = _log.Count(); + frame = Log.Count(); } for (int i = 0; i < count; i++) { - _log.Insert(frame, lg.EmptyEntry); + Log.Insert(frame, lg.EmptyEntry); } if (BindMarkersToInput) @@ -380,7 +380,7 @@ namespace BizHawk.Client.Common ChangeLog.EndBatch(); } - if (Global.Emulator.Frame < _log.Count) // Don't stay in recording mode? Fixes TAStudio recording after paint inserting. + if (Global.Emulator.Frame < Log.Count) // Don't stay in recording mode? Fixes TAStudio recording after paint inserting. { SwitchToPlay(); } @@ -399,7 +399,7 @@ namespace BizHawk.Client.Common for (int i = 0; i < numFrames; i++) { - _log.Add(lg.GenerateLogEntry()); + Log.Add(lg.GenerateLogEntry()); } Changes = true; @@ -410,7 +410,7 @@ namespace BizHawk.Client.Common ChangeLog.EndBatch(); } - if (Global.Emulator.Frame < _log.Count) // Don't stay in recording mode? Fixes TAStudio recording after paint inserting. + if (Global.Emulator.Frame < Log.Count) // Don't stay in recording mode? Fixes TAStudio recording after paint inserting. { SwitchToPlay(); } @@ -418,9 +418,9 @@ namespace BizHawk.Client.Common public void ToggleBoolState(int frame, string buttonName) { - if (frame >= _log.Count) // Insert blank frames up to this point + if (frame >= Log.Count) // Insert blank frames up to this point { - ExtendMovieForEdit(frame - _log.Count + 1); + ExtendMovieForEdit(frame - Log.Count + 1); } var adapter = GetInputState(frame) as Bk2ControllerAdapter; @@ -428,7 +428,7 @@ namespace BizHawk.Client.Common var lg = LogGeneratorInstance(); lg.SetSource(adapter); - _log[frame] = lg.GenerateLogEntry(); + Log[frame] = lg.GenerateLogEntry(); Changes = true; InvalidateAfter(frame); @@ -437,9 +437,9 @@ namespace BizHawk.Client.Common public void SetBoolState(int frame, string buttonName, bool val) { - if (frame >= _log.Count) // Insert blank frames up to this point + if (frame >= Log.Count) // Insert blank frames up to this point { - ExtendMovieForEdit(frame - _log.Count + 1); + ExtendMovieForEdit(frame - Log.Count + 1); } var adapter = GetInputState(frame) as Bk2ControllerAdapter; @@ -448,7 +448,7 @@ namespace BizHawk.Client.Common var lg = LogGeneratorInstance(); lg.SetSource(adapter); - _log[frame] = lg.GenerateLogEntry(); + Log[frame] = lg.GenerateLogEntry(); if (old != val) { @@ -460,9 +460,9 @@ namespace BizHawk.Client.Common public void SetBoolStates(int frame, int count, string buttonName, bool val) { - if (frame + count >= _log.Count) // Insert blank frames up to this point + if (Log.Count < frame + count) { - ExtendMovieForEdit(frame - _log.Count + 1); + ExtendMovieForEdit(frame + count - Log.Count); } ChangeLog.AddGeneralUndo(frame, frame + count - 1, "Set " + buttonName + "(" + (val ? "On" : "Off") + "): " + frame + "-" + (frame + count - 1)); @@ -476,7 +476,7 @@ namespace BizHawk.Client.Common var lg = LogGeneratorInstance(); lg.SetSource(adapter); - _log[frame + i] = lg.GenerateLogEntry(); + Log[frame + i] = lg.GenerateLogEntry(); if (changed == -1 && old != val) { @@ -495,9 +495,9 @@ namespace BizHawk.Client.Common public void SetFloatState(int frame, string buttonName, float val) { - if (frame >= _log.Count) // Insert blank frames up to this point + if (frame >= Log.Count) // Insert blank frames up to this point { - ExtendMovieForEdit(frame - _log.Count + 1); + ExtendMovieForEdit(frame - Log.Count + 1); } var adapter = GetInputState(frame) as Bk2ControllerAdapter; @@ -506,7 +506,7 @@ namespace BizHawk.Client.Common var lg = LogGeneratorInstance(); lg.SetSource(adapter); - _log[frame] = lg.GenerateLogEntry(); + Log[frame] = lg.GenerateLogEntry(); if (old != val) { @@ -518,9 +518,9 @@ namespace BizHawk.Client.Common public void SetFloatStates(int frame, int count, string buttonName, float val) { - if (frame + count >= _log.Count) // Insert blank frames up to this point + if (frame + count >= Log.Count) // Insert blank frames up to this point { - ExtendMovieForEdit(frame - _log.Count + 1); + ExtendMovieForEdit(frame - Log.Count + 1); } ChangeLog.AddGeneralUndo(frame, frame + count - 1, "Set " + buttonName + "(" + val + "): " + frame + "-" + (frame + count - 1)); @@ -534,7 +534,7 @@ namespace BizHawk.Client.Common var lg = LogGeneratorInstance(); lg.SetSource(adapter); - _log[frame + i] = lg.GenerateLogEntry(); + Log[frame + i] = lg.GenerateLogEntry(); if (changed == -1 && old != val) { diff --git a/BizHawk.Client.Common/movie/tasproj/TasMovie.History.cs b/BizHawk.Client.Common/movie/tasproj/TasMovie.History.cs index 4ec37754c4..30f6182037 100644 --- a/BizHawk.Client.Common/movie/tasproj/TasMovie.History.cs +++ b/BizHawk.Client.Common/movie/tasproj/TasMovie.History.cs @@ -6,10 +6,21 @@ namespace BizHawk.Client.Common { public class TasMovieChangeLog { - private readonly List> History; - public List Names; - public int UndoIndex = -1; + public TasMovieChangeLog(TasMovie movie) + { + _history = new List>(); + _movie = movie; + } + + private readonly List> _history = new List>(); + private readonly TasMovie _movie; + private int _maxSteps = 100; + private int _totalSteps; + private bool _recordingBatch; + + public List Names { get; } = new List(); + public int UndoIndex { get; private set; } = -1; public int MaxSteps { @@ -21,46 +32,35 @@ namespace BizHawk.Client.Common set { _maxSteps = value; - if (History.Count > value) + if (_history.Count > value) { - if (History.Count <= value) + if (_history.Count <= value) { ClearLog(); } else { - ClearLog(History.Count - value); + ClearLog(_history.Count - value); } } } } - private int _totalSteps = 0; - private bool RecordingBatch = false; - /// + /// Gets or sets a value indicating whether the movie is in recording mode /// This is not intended to turn off the ChangeLog, but to disable the normal recording process. /// Use this to manually control the ChangeLog. (Useful for when you are making lots of /// - public bool IsRecording = true; - - public TasMovie Movie; - - public TasMovieChangeLog(TasMovie movie) - { - History = new List>(); - Names = new List(); - Movie = movie; - } + public bool IsRecording { get; set; } = true; public void ClearLog(int upTo = -1) { if (upTo == -1) { - upTo = History.Count; + upTo = _history.Count; } - History.RemoveRange(0, upTo); + _history.RemoveRange(0, upTo); Names.RemoveRange(0, upTo); UndoIndex -= upTo; if (UndoIndex < -1) @@ -68,25 +68,25 @@ namespace BizHawk.Client.Common UndoIndex = -1; } - if (History.Count == 0) + if (_history.Count == 0) { - RecordingBatch = false; + _recordingBatch = false; } } private void TruncateLog(int from) { - History.RemoveRange(from, History.Count - from); + _history.RemoveRange(from, _history.Count - from); Names.RemoveRange(from, Names.Count - from); - if (UndoIndex < History.Count - 1) + if (UndoIndex < _history.Count - 1) { - UndoIndex = History.Count - 1; + UndoIndex = _history.Count - 1; } - if (RecordingBatch) + if (_recordingBatch) { - RecordingBatch = false; + _recordingBatch = false; BeginNewBatch(); } } @@ -106,7 +106,7 @@ namespace BizHawk.Client.Common } bool ret = true; - if (RecordingBatch) + if (_recordingBatch) { if (keepOldBatch) { @@ -123,7 +123,7 @@ namespace BizHawk.Client.Common ret = AddMovieAction(name); } - RecordingBatch = true; + _recordingBatch = true; return ret; } @@ -134,16 +134,16 @@ namespace BizHawk.Client.Common /// public void EndBatch() { - if (!IsRecording || !RecordingBatch) + if (!IsRecording || !_recordingBatch) { return; } - RecordingBatch = false; - List last = History.Last(); + _recordingBatch = false; + List last = _history.Last(); if (last.Count == 0) // Remove batch if it's empty. { - History.RemoveAt(History.Count - 1); + _history.RemoveAt(_history.Count - 1); Names.RemoveAt(Names.Count - 1); UndoIndex--; } @@ -161,22 +161,22 @@ namespace BizHawk.Client.Common { if (UndoIndex == -1) { - return Movie.InputLogLength; + return _movie.InputLogLength; } - List batch = History[UndoIndex]; + List batch = _history[UndoIndex]; for (int i = batch.Count - 1; i >= 0; i--) { - batch[i].Undo(Movie); + batch[i].Undo(_movie); } UndoIndex--; - RecordingBatch = false; + _recordingBatch = false; if (batch.All(a => a.GetType() == typeof(MovieActionMarker))) { - return Movie.InputLogLength; + return _movie.InputLogLength; } return PreviousUndoFrame; @@ -188,30 +188,30 @@ namespace BizHawk.Client.Common /// Returns the frame which the movie needs to rewind to. public int Redo() { - if (UndoIndex == History.Count - 1) + if (UndoIndex == _history.Count - 1) { - return Movie.InputLogLength; + return _movie.InputLogLength; } UndoIndex++; - List batch = History[UndoIndex]; + List batch = _history[UndoIndex]; foreach (IMovieAction b in batch) { - b.Redo(Movie); + b.Redo(_movie); } - RecordingBatch = false; + _recordingBatch = false; if (batch.All(a => a.GetType() == typeof(MovieActionMarker))) { - return Movie.InputLogLength; + return _movie.InputLogLength; } return PreviousRedoFrame; } public bool CanUndo => UndoIndex > -1; - public bool CanRedo => UndoIndex < History.Count - 1; + public bool CanRedo => UndoIndex < _history.Count - 1; public string NextUndoStepName { @@ -230,17 +230,17 @@ namespace BizHawk.Client.Common { get { - if (UndoIndex == History.Count - 1) + if (UndoIndex == _history.Count - 1) { - return Movie.InputLogLength; + return _movie.InputLogLength; } - if (History[UndoIndex + 1].Count == 0) + if (_history[UndoIndex + 1].Count == 0) { - return Movie.InputLogLength; + return _movie.InputLogLength; } - return History[UndoIndex + 1].Min(a => a.FirstFrame); + return _history[UndoIndex + 1].Min(a => a.FirstFrame); } } @@ -250,15 +250,15 @@ namespace BizHawk.Client.Common { if (UndoIndex == -1) { - return Movie.InputLogLength; + return _movie.InputLogLength; } - if (History[UndoIndex].Count == 0) + if (_history[UndoIndex].Count == 0) { - return Movie.InputLogLength; + return _movie.InputLogLength; } - return History[UndoIndex].Min(a => a.FirstFrame); + return _history[UndoIndex].Min(a => a.FirstFrame); } } @@ -266,7 +266,7 @@ namespace BizHawk.Client.Common private bool AddMovieAction(string name) { - if (UndoIndex + 1 != History.Count) + if (UndoIndex + 1 != _history.Count) { TruncateLog(UndoIndex + 1); } @@ -277,20 +277,20 @@ namespace BizHawk.Client.Common } bool ret = false; - if (!RecordingBatch) + if (!_recordingBatch) { ret = true; - History.Add(new List(1)); + _history.Add(new List(1)); Names.Add(name); _totalSteps += 1; - if (History.Count <= MaxSteps) + if (_history.Count <= MaxSteps) { UndoIndex += 1; } else { - History.RemoveAt(0); + _history.RemoveAt(0); Names.RemoveAt(0); ret = false; } @@ -312,8 +312,8 @@ namespace BizHawk.Client.Common if (IsRecording || force) { AddMovieAction(name); - History.Last().Add(new MovieAction(first, last, Movie)); - _lastGeneral = History.Last().Count - 1; + _history.Last().Add(new MovieAction(first, last, _movie)); + _lastGeneral = _history.Last().Count - 1; } } @@ -321,7 +321,7 @@ namespace BizHawk.Client.Common { if (IsRecording || force) { - (History.Last()[_lastGeneral] as MovieAction).SetRedoLog(Movie); + (_history.Last()[_lastGeneral] as MovieAction).SetRedoLog(_movie); } } @@ -330,7 +330,7 @@ namespace BizHawk.Client.Common if (IsRecording || force) { AddMovieAction(name); - History.Last().Add(new MovieActionFrameEdit(frame, button, oldState, !oldState)); + _history.Last().Add(new MovieActionFrameEdit(frame, button, oldState, !oldState)); } } @@ -339,11 +339,11 @@ namespace BizHawk.Client.Common if (IsRecording || force) { AddMovieAction(name); - History.Last().Add(new MovieActionFrameEdit(frame, button, oldState, newState)); + _history.Last().Add(new MovieActionFrameEdit(frame, button, oldState, newState)); } } - public void AddMarkerChange(TasMovieMarker newMarker, int oldPosition = -1, string old_message = "", string name = "", bool force = false) + public void AddMarkerChange(TasMovieMarker newMarker, int oldPosition = -1, string oldMessage = "", string name = "", bool force = false) { if (IsRecording || force) { @@ -357,7 +357,7 @@ namespace BizHawk.Client.Common } AddMovieAction(name); - History.Last().Add(new MovieActionMarker(newMarker, oldPosition, old_message)); + _history.Last().Add(new MovieActionMarker(newMarker, oldPosition, oldMessage)); } } @@ -366,7 +366,7 @@ namespace BizHawk.Client.Common if (IsRecording || force) { AddMovieAction(name); - History.Last().Add(new MovieActionBindInput(Movie, frame, isDelete)); + _history.Last().Add(new MovieActionBindInput(_movie, frame, isDelete)); } } @@ -392,7 +392,7 @@ namespace BizHawk.Client.Common private readonly int _undoLength; private int _redoLength; - private int length => LastFrame - FirstFrame + 1; + private int Length => LastFrame - FirstFrame + 1; private readonly List _oldLog; private List _newLog; @@ -402,7 +402,7 @@ namespace BizHawk.Client.Common { FirstFrame = firstFrame; LastFrame = lastFrame; - _oldLog = new List(length); + _oldLog = new List(Length); _undoLength = Math.Min(LastFrame + 1, movie.InputLogLength) - FirstFrame; for (int i = 0; i < _undoLength; i++) @@ -430,12 +430,12 @@ namespace BizHawk.Client.Common movie.ChangeLog.IsRecording = false; movie.BindMarkersToInput = _bindMarkers; - if (_redoLength != length) + if (_redoLength != Length) { - movie.InsertEmptyFrame(FirstFrame, length - _redoLength, true); + movie.InsertEmptyFrame(FirstFrame, Length - _redoLength, true); } - if (_undoLength != length) + if (_undoLength != Length) { movie.RemoveFrames(FirstFrame, movie.InputLogLength - _undoLength, true); } @@ -456,12 +456,12 @@ namespace BizHawk.Client.Common movie.ChangeLog.IsRecording = false; movie.BindMarkersToInput = _bindMarkers; - if (_undoLength != length) + if (_undoLength != Length) { - movie.InsertEmptyFrame(FirstFrame, length - _undoLength); + movie.InsertEmptyFrame(FirstFrame, Length - _undoLength); } - if (_redoLength != length) + if (_redoLength != Length) { movie.RemoveFrames(FirstFrame, movie.InputLogLength - _redoLength); } @@ -484,18 +484,18 @@ namespace BizHawk.Client.Common private readonly string _oldMessage; private readonly string _newMessage; - public MovieActionMarker(TasMovieMarker marker, int oldPosition = -1, string old_message = "") + public MovieActionMarker(TasMovieMarker marker, int oldPosition = -1, string oldMessage = "") { FirstFrame = oldPosition; if (marker == null) { LastFrame = -1; - _oldMessage = old_message; + _oldMessage = oldMessage; } else { LastFrame = marker.Frame; - _oldMessage = old_message == "" ? marker.Message : old_message; + _oldMessage = oldMessage == "" ? marker.Message : oldMessage; _newMessage = marker.Message; } } diff --git a/BizHawk.Client.Common/movie/tasproj/TasMovie.cs b/BizHawk.Client.Common/movie/tasproj/TasMovie.cs index 735fe22449..ed41d86b61 100644 --- a/BizHawk.Client.Common/movie/tasproj/TasMovie.cs +++ b/BizHawk.Client.Common/movie/tasproj/TasMovie.cs @@ -31,7 +31,7 @@ namespace BizHawk.Client.Common public TasLagLog TasLagLog => _lagLog; - public IStringLog InputLog => _log; + public IStringLog InputLog => Log; public TasMovieMarkerList Markers { get; private set; } @@ -139,12 +139,12 @@ namespace BizHawk.Client.Common public override void SwitchToPlay() { - _mode = Moviemode.Play; + Mode = Moviemode.Play; } public override void SwitchToRecord() { - _mode = Moviemode.Record; + Mode = Moviemode.Record; } /// @@ -250,18 +250,18 @@ namespace BizHawk.Client.Common public void DeleteLogBefore(int frame) { - if (frame < _log.Count) + if (frame < Log.Count) { - _log.RemoveRange(0, frame); + Log.RemoveRange(0, frame); } } public void CopyLog(IEnumerable log) { - _log.Clear(); + Log.Clear(); foreach (var entry in log) { - _log.Add(entry); + Log.Add(entry); } } @@ -275,10 +275,10 @@ namespace BizHawk.Client.Common public IStringLog GetLogEntries() { - return _log; + return Log; } - private int? TimelineBranchFrame = null; + private int? _timelineBranchFrame = null; // TODO: this is 99% copy pasting of bad code public override bool ExtractInputLog(TextReader reader, out string errorMessage) @@ -291,9 +291,9 @@ namespace BizHawk.Client.Common // We are in record mode so replace the movie log with the one from the savestate if (!Global.MovieSession.MultiTrack.IsActive) { - TimelineBranchFrame = null; + _timelineBranchFrame = null; - if (Global.Config.EnableBackupMovies && MakeBackup && _log.Count != 0) + if (Global.Config.EnableBackupMovies && MakeBackup && Log.Count != 0) { SaveBackup(); MakeBackup = false; @@ -341,17 +341,17 @@ namespace BizHawk.Client.Common else if (line[0] == '|') { newLog.Add(line); - if (!TimelineBranchFrame.HasValue && counter < _log.Count && line != _log[counter]) + if (!_timelineBranchFrame.HasValue && counter < Log.Count && line != Log[counter]) { - TimelineBranchFrame = counter; + _timelineBranchFrame = counter; } counter++; } } - _log.Clear(); - _log.AddRange(newLog); + Log.Clear(); + Log.AddRange(newLog); } else // Multitrack mode { @@ -410,21 +410,21 @@ namespace BizHawk.Client.Common var stateFramei = stateFrame ?? 0; - if (stateFramei > 0 && stateFramei < _log.Count) + if (stateFramei > 0 && stateFramei < Log.Count) { if (!Global.Config.VBAStyleMovieLoadState) { Truncate(stateFramei); } } - else if (stateFramei > _log.Count) // Post movie savestate + else if (stateFramei > Log.Count) // Post movie savestate { if (!Global.Config.VBAStyleMovieLoadState) { - Truncate(_log.Count); + Truncate(Log.Count); } - _mode = Moviemode.Finished; + Mode = Moviemode.Finished; } if (IsCountingRerecords) @@ -432,10 +432,10 @@ namespace BizHawk.Client.Common Rerecords++; } - if (TimelineBranchFrame.HasValue) + if (_timelineBranchFrame.HasValue) { - _lagLog.RemoveFrom(TimelineBranchFrame.Value); - TasStateManager.Invalidate(TimelineBranchFrame.Value); + _lagLog.RemoveFrom(_timelineBranchFrame.Value); + TasStateManager.Invalidate(_timelineBranchFrame.Value); } return true; @@ -510,10 +510,10 @@ namespace BizHawk.Client.Common public void LoadBranch(TasBranch branch) { - int? divergentPoint = DivergentPoint(_log, branch.InputLog); + int? divergentPoint = DivergentPoint(Log, branch.InputLog); - _log?.Dispose(); - _log = branch.InputLog.Clone(); + Log?.Dispose(); + Log = branch.InputLog.Clone(); ////_changes = true; // if there are branch states, they will be loaded anyway diff --git a/BizHawk.Client.Common/movie/tasproj/TasStateManager.cs b/BizHawk.Client.Common/movie/tasproj/TasStateManager.cs index cfa4af1c6c..b4fe3b0138 100644 --- a/BizHawk.Client.Common/movie/tasproj/TasStateManager.cs +++ b/BizHawk.Client.Common/movie/tasproj/TasStateManager.cs @@ -26,26 +26,26 @@ namespace BizHawk.Client.Common InvalidateCallback?.Invoke(index); } - private readonly List lowPriorityStates = new List(); - internal NDBDatabase ndbdatabase; - private Guid guid = Guid.NewGuid(); - private SortedList States = new SortedList(); + private readonly List _lowPriorityStates = new List(); + internal NDBDatabase NdbDatabase { get; set; } + private Guid _guid = Guid.NewGuid(); + private SortedList _states = new SortedList(); - private string statePath + private string StatePath { get { var basePath = PathManager.MakeAbsolutePath(Global.Config.PathEntries["Global", "TAStudio states"].Path, null); - return Path.Combine(basePath, guid.ToString()); + return Path.Combine(basePath, _guid.ToString()); } } private bool _isMountedForWrite; private readonly TasMovie _movie; - private ulong _expectedStateSize = 0; + private ulong _expectedStateSize; private readonly int _minFrequency = VersionInfo.DeveloperBuild ? 2 : 1; - private const int _maxFrequency = 16; + private const int MaxFrequency = 16; private int StateFrequency { @@ -58,18 +58,18 @@ namespace BizHawk.Client.Common return _minFrequency; } - if (freq > _maxFrequency) + if (freq > MaxFrequency) { - return _maxFrequency; + return MaxFrequency; } return freq; } } - private int maxStates => (int)(Settings.Cap / _expectedStateSize) + (int)((ulong)Settings.DiskCapacitymb * 1024 * 1024 / _expectedStateSize); + private int MaxStates => (int)(Settings.Cap / _expectedStateSize) + (int)((ulong)Settings.DiskCapacitymb * 1024 * 1024 / _expectedStateSize); - private int _stateGap => 1 << Settings.StateGap; + private int StateGap => 1 << Settings.StateGap; public TasStateManager(TasMovie movie) { @@ -77,7 +77,7 @@ namespace BizHawk.Client.Common Settings = new TasStateManagerSettings(Global.Config.DefaultTasProjSettings); - accessed = new List(); + _accessed = new List(); if (_movie.StartsFromSavestate) { @@ -88,7 +88,7 @@ namespace BizHawk.Client.Common public void Dispose() { // States and BranchStates don't need cleaning because they would only contain an ndbdatabase entry which was demolished by the below - ndbdatabase?.Dispose(); + NdbDatabase?.Dispose(); } /// @@ -109,17 +109,17 @@ namespace BizHawk.Client.Common if (_expectedStateSize > 0) { - limit = maxStates; + limit = MaxStates; } - States = new SortedList(limit); + _states = new SortedList(limit); if (_expectedStateSize > int.MaxValue) { throw new InvalidOperationException(); } - ndbdatabase = new NDBDatabase(statePath, Settings.DiskCapacitymb * 1024 * 1024, (int)_expectedStateSize); + NdbDatabase = new NDBDatabase(StatePath, Settings.DiskCapacitymb * 1024 * 1024, (int)_expectedStateSize); } public TasStateManagerSettings Settings { get; set; } @@ -138,17 +138,17 @@ namespace BizHawk.Client.Common return new KeyValuePair(0, InitialState); } - if (States.ContainsKey(frame)) + if (_states.ContainsKey(frame)) { StateAccessed(frame); - return new KeyValuePair(frame, States[frame].State); + return new KeyValuePair(frame, _states[frame].State); } return new KeyValuePair(-1, new byte[0]); } } - private readonly List accessed; + private readonly List _accessed; public byte[] InitialState { @@ -159,7 +159,7 @@ namespace BizHawk.Client.Common return _movie.BinarySavestate; } - return States[0].State; + return _states[0].State; } } @@ -169,7 +169,7 @@ namespace BizHawk.Client.Common /// public void Capture(bool force = false) { - bool shouldCapture = false; + bool shouldCapture; int frame = Global.Emulator.Frame; if (_movie.StartsFromSavestate && frame == 0) // Never capture frame 0 on savestate anchored movies since we have it anyway @@ -215,8 +215,8 @@ namespace BizHawk.Client.Common { lastMemState++; } - while (States[accessed[lastMemState].Frame] == null); - MoveStateToDisk(accessed[lastMemState].Frame); + while (_states[_accessed[lastMemState].Frame] == null); + MoveStateToDisk(_accessed[lastMemState].Frame); } } @@ -228,9 +228,9 @@ namespace BizHawk.Client.Common // X is frame, Y is branch Point shouldRemove = new Point(-1, -1); - if (BranchStates.Any() && Settings.EraseBranchStatesFirst) + if (_branchStates.Any() && Settings.EraseBranchStatesFirst) { - var kvp = BranchStates.Count > 1 ? BranchStates.ElementAt(1) : BranchStates.ElementAt(0); + var kvp = _branchStates.Count > 1 ? _branchStates.ElementAt(1) : _branchStates.ElementAt(0); shouldRemove.X = kvp.Key; shouldRemove.Y = kvp.Value.Keys[0]; @@ -238,14 +238,14 @@ namespace BizHawk.Client.Common } int i = 0; - int markerSkips = maxStates / 2; + int markerSkips = MaxStates / 2; // lowPrioritySates (e.g. states with only lag frames between them) do { - if (lowPriorityStates.Count > i) + if (_lowPriorityStates.Count > i) { - shouldRemove = findState(lowPriorityStates[i]); + shouldRemove = FindState(_lowPriorityStates[i]); } else { @@ -261,18 +261,18 @@ namespace BizHawk.Client.Common i++; } - while (StateIsMarker(shouldRemove.X, shouldRemove.Y) && markerSkips > -1 || shouldRemove.X == 0); + while ((StateIsMarker(shouldRemove.X, shouldRemove.Y) && markerSkips > -1) || shouldRemove.X == 0); // by last accessed - markerSkips = maxStates / 2; + markerSkips = MaxStates / 2; if (shouldRemove.X < 1) { i = 0; do { - if (accessed.Count > i) + if (_accessed.Count > i) { - shouldRemove = findState(accessed[i]); + shouldRemove = FindState(_accessed[i]); } else { @@ -288,20 +288,20 @@ namespace BizHawk.Client.Common i++; } - while (StateIsMarker(shouldRemove.X, shouldRemove.Y) && markerSkips > -1 || shouldRemove.X == 0); + while ((StateIsMarker(shouldRemove.X, shouldRemove.Y) && markerSkips > -1) || shouldRemove.X == 0); } if (shouldRemove.X < 1) // only found marker states above { - if (BranchStates.Any() && !Settings.EraseBranchStatesFirst) + if (_branchStates.Any() && !Settings.EraseBranchStatesFirst) { - var kvp = BranchStates.Count > 1 ? BranchStates.ElementAt(1) : BranchStates.ElementAt(0); + var kvp = _branchStates.Count > 1 ? _branchStates.ElementAt(1) : _branchStates.ElementAt(0); shouldRemove.X = kvp.Key; shouldRemove.Y = kvp.Value.Keys[0]; } else { - StateManagerState s = States.Values[1]; + StateManagerState s = _states.Values[1]; shouldRemove.X = s.Frame; shouldRemove.Y = -1; } @@ -319,12 +319,12 @@ namespace BizHawk.Client.Common if (branch == -1) { - return _movie.Markers.IsMarker(States[frame].Frame + 1); + return _movie.Markers.IsMarker(_states[frame].Frame + 1); } if (_movie.GetBranch(_movie.BranchIndexByHash(branch)).Markers == null) { - return _movie.Markers.IsMarker(States[frame].Frame + 1); + return _movie.Markers.IsMarker(_states[frame].Frame + 1); } return _movie.GetBranch(branch).Markers.Any(m => m.Frame + 1 == frame); @@ -354,14 +354,14 @@ namespace BizHawk.Client.Common private void MoveStateToDisk(int index) { - Used -= (ulong)States[index].Length; - States[index].MoveToDisk(); + Used -= (ulong)_states[index].Length; + _states[index].MoveToDisk(); } private void MoveStateToMemory(int index) { - States[index].MoveToRAM(); - Used += (ulong)States[index].Length; + _states[index].MoveToRAM(); + Used += (ulong)_states[index].Length; } internal void SetState(int frame, byte[] state, bool skipRemoval = true) @@ -371,27 +371,27 @@ namespace BizHawk.Client.Common MaybeRemoveStates(); // Remove before adding so this state won't be removed. } - if (States.ContainsKey(frame)) + if (_states.ContainsKey(frame)) { - if (stateHasDuplicate(frame, -1) != -2) + if (StateHasDuplicate(frame, -1) != -2) { Used += (ulong)state.Length; } - States[frame].State = state; + _states[frame].State = state; } else { Used += (ulong)state.Length; - States.Add(frame, new StateManagerState(this, state, frame)); + _states.Add(frame, new StateManagerState(this, state, frame)); } StateAccessed(frame); - int i = States.IndexOfKey(frame); - if (i > 0 && AllLag(States.Keys[i - 1], States.Keys[i])) + int i = _states.IndexOfKey(frame); + if (i > 0 && AllLag(_states.Keys[i - 1], _states.Keys[i])) { - lowPriorityStates.Add(States[frame]); + _lowPriorityStates.Add(_states[frame]); } } @@ -399,49 +399,49 @@ namespace BizHawk.Client.Common { if (branch == -1) { - accessed.Remove(States[frame]); + _accessed.Remove(_states[frame]); } - else if (accessed.Contains(BranchStates[frame][branch]) && !Settings.EraseBranchStatesFirst) + else if (_accessed.Contains(_branchStates[frame][branch]) && !Settings.EraseBranchStatesFirst) { - accessed.Remove(BranchStates[frame][branch]); + _accessed.Remove(_branchStates[frame][branch]); } StateManagerState state; - bool hasDuplicate = stateHasDuplicate(frame, branch) != -2; + bool hasDuplicate = StateHasDuplicate(frame, branch) != -2; if (branch == -1) { - state = States[frame]; - if (States[frame].IsOnDisk) + state = _states[frame]; + if (_states[frame].IsOnDisk) { - States[frame].Dispose(); + _states[frame].Dispose(); } else { - Used -= (ulong)States[frame].Length; + Used -= (ulong)_states[frame].Length; } - States.RemoveAt(States.IndexOfKey(frame)); + _states.RemoveAt(_states.IndexOfKey(frame)); } else { - state = BranchStates[frame][branch]; + state = _branchStates[frame][branch]; - if (BranchStates[frame][branch].IsOnDisk) + if (_branchStates[frame][branch].IsOnDisk) { - BranchStates[frame][branch].Dispose(); + _branchStates[frame][branch].Dispose(); } - BranchStates[frame].RemoveAt(BranchStates[frame].IndexOfKey(branch)); + _branchStates[frame].RemoveAt(_branchStates[frame].IndexOfKey(branch)); - if (BranchStates[frame].Count == 0) + if (_branchStates[frame].Count == 0) { - BranchStates.Remove(frame); + _branchStates.Remove(frame); } } if (!hasDuplicate) { - lowPriorityStates.Remove(state); + _lowPriorityStates.Remove(state); } } @@ -452,23 +452,23 @@ namespace BizHawk.Client.Common return; } - StateManagerState state = States[frame]; - bool removed = accessed.Remove(state); - accessed.Add(state); + StateManagerState state = _states[frame]; + bool removed = _accessed.Remove(state); + _accessed.Add(state); - if (States[frame].IsOnDisk) + if (_states[frame].IsOnDisk) { - if (!States[accessed[0].Frame].IsOnDisk) + if (!_states[_accessed[0].Frame].IsOnDisk) { - MoveStateToDisk(accessed[0].Frame); + MoveStateToDisk(_accessed[0].Frame); } MoveStateToMemory(frame); } - if (!removed && accessed.Count > maxStates) + if (!removed && _accessed.Count > MaxStates) { - accessed.RemoveAt(0); + _accessed.RemoveAt(0); } } @@ -479,7 +479,7 @@ namespace BizHawk.Client.Common return true; } - return States.ContainsKey(frame); + return _states.ContainsKey(frame); } /// @@ -497,7 +497,7 @@ namespace BizHawk.Client.Common } List> statesToRemove = - States.Where(s => s.Key >= frame).ToList(); + _states.Where(s => s.Key >= frame).ToList(); anyInvalidated = statesToRemove.Any(); @@ -517,21 +517,21 @@ namespace BizHawk.Client.Common /// public void Clear() { - States.Clear(); - accessed.Clear(); + _states.Clear(); + _accessed.Clear(); Used = 0; ClearDiskStates(); } public void ClearStateHistory() { - if (States.Any()) + if (_states.Any()) { - StateManagerState power = States.Values.FirstOrDefault(s => s.Frame == 0); + StateManagerState power = _states.Values.First(s => s.Frame == 0); StateAccessed(power.Frame); - States.Clear(); - accessed.Clear(); + _states.Clear(); + _accessed.Clear(); SetState(0, power.State); Used = (ulong)power.State.Length; @@ -542,7 +542,7 @@ namespace BizHawk.Client.Common private void ClearDiskStates() { - ndbdatabase?.Clear(); + NdbDatabase?.Clear(); } /// @@ -564,9 +564,9 @@ namespace BizHawk.Client.Common { index++; } - while (!accessed[index].IsOnDisk); + while (!_accessed[index].IsOnDisk); - accessed[index].MoveToRAM(); + _accessed[index].MoveToRAM(); } if (Used > Settings.Cap) @@ -582,23 +582,23 @@ namespace BizHawk.Client.Common // respect state gap no matter how small the resulting size will be // still leave marker states - for (int i = 1; i < States.Count; i++) + for (int i = 1; i < _states.Count; i++) { - if (_movie.Markers.IsMarker(States.ElementAt(i).Key + 1) - || States.ElementAt(i).Key % _stateGap == 0) + if (_movie.Markers.IsMarker(_states.ElementAt(i).Key + 1) + || _states.ElementAt(i).Key % StateGap == 0) { continue; } ret.Add(i); - if (States.ElementAt(i).Value.IsOnDisk) + if (_states.ElementAt(i).Value.IsOnDisk) { saveUsed -= _expectedStateSize; } else { - saveUsed -= (ulong)States.ElementAt(i).Value.Length; + saveUsed -= (ulong)_states.ElementAt(i).Value.Length; } } @@ -610,27 +610,27 @@ namespace BizHawk.Client.Common do { index++; - if (index >= States.Count) + if (index >= _states.Count) { break; } } - while (_movie.Markers.IsMarker(States.ElementAt(index).Key + 1)); + while (_movie.Markers.IsMarker(_states.ElementAt(index).Key + 1)); - if (index >= States.Count) + if (index >= _states.Count) { break; } ret.Add(index); - if (States.ElementAt(index).Value.IsOnDisk) + if (_states.ElementAt(index).Value.IsOnDisk) { saveUsed -= _expectedStateSize; } else { - saveUsed -= (ulong)States.ElementAt(index).Value.Length; + saveUsed -= (ulong)_states.ElementAt(index).Value.Length; } } @@ -644,13 +644,13 @@ namespace BizHawk.Client.Common ret.Add(index); } - if (States.ElementAt(index).Value.IsOnDisk) + if (_states.ElementAt(index).Value.IsOnDisk) { saveUsed -= _expectedStateSize; } else { - saveUsed -= (ulong)States.ElementAt(index).Value.Length; + saveUsed -= (ulong)_states.ElementAt(index).Value.Length; } } @@ -661,16 +661,16 @@ namespace BizHawk.Client.Common { List noSave = ExcludeStates(); - bw.Write(States.Count - noSave.Count); - for (int i = 0; i < States.Count; i++) + bw.Write(_states.Count - noSave.Count); + for (int i = 0; i < _states.Count; i++) { if (noSave.Contains(i)) { continue; } - StateAccessed(States.ElementAt(i).Key); - KeyValuePair kvp = States.ElementAt(i); + StateAccessed(_states.ElementAt(i).Key); + KeyValuePair kvp = _states.ElementAt(i); bw.Write(kvp.Key); bw.Write(kvp.Value.Length); bw.Write(kvp.Value.State); @@ -680,7 +680,7 @@ namespace BizHawk.Client.Common public void Load(BinaryReader br) { - States.Clear(); + _states.Clear(); try { int nstates = br.ReadInt32(); @@ -704,8 +704,8 @@ namespace BizHawk.Client.Common public void SaveBranchStates(BinaryWriter bw) { - bw.Write(BranchStates.Count); - foreach (var s in BranchStates) + bw.Write(_branchStates.Count); + foreach (var s in _branchStates) { bw.Write(s.Key); bw.Write(s.Value.Count); @@ -722,7 +722,7 @@ namespace BizHawk.Client.Common try { int c = br.ReadInt32(); - BranchStates = new SortedList>(c); + _branchStates = new SortedList>(c); while (c > 0) { int key = br.ReadInt32(); @@ -736,7 +736,7 @@ namespace BizHawk.Client.Common c2--; } - BranchStates.Add(key, list); + _branchStates.Add(key, list); c--; } } @@ -748,7 +748,7 @@ namespace BizHawk.Client.Common public KeyValuePair GetStateClosestToFrame(int frame) { - var s = States.LastOrDefault(state => state.Key < frame); + var s = _states.LastOrDefault(state => state.Key < frame); return this[s.Key]; } @@ -785,37 +785,37 @@ namespace BizHawk.Client.Common { get { - if (ndbdatabase == null) + if (NdbDatabase == null) { return 0; } - return (ulong)ndbdatabase.Consumed; + return (ulong)NdbDatabase.Consumed; } } - public int StateCount => States.Count; + public int StateCount => _states.Count; public bool Any() { if (_movie.StartsFromSavestate) { - return States.Count > 0; + return _states.Count > 0; } - return States.Count > 1; + return _states.Count > 1; } public int LastKey { get { - if (States.Count == 0) + if (_states.Count == 0) { return 0; } - return States.Last().Key; + return _states.Last().Key; } } @@ -834,45 +834,45 @@ namespace BizHawk.Client.Common #region Branches - private SortedList> BranchStates = new SortedList>(); + private SortedList> _branchStates = new SortedList>(); /// /// Checks if the state at frame in the given branch (-1 for current) has any duplicates. /// /// Index of the branch (-1 for current) of the first match. If no match, returns -2. - private int stateHasDuplicate(int frame, int branchHash) + private int StateHasDuplicate(int frame, int branchHash) { StateManagerState stateToMatch; // Get the state instance if (branchHash == -1) { - stateToMatch = States[frame]; + stateToMatch = _states[frame]; } else { - if (!BranchStates[frame].ContainsKey(branchHash)) + if (!_branchStates[frame].ContainsKey(branchHash)) { return -2; } - stateToMatch = BranchStates[frame][branchHash]; + stateToMatch = _branchStates[frame][branchHash]; // Check the current branch for duplicate. - if (States.ContainsKey(frame) && States[frame] == stateToMatch) + if (_states.ContainsKey(frame) && _states[frame] == stateToMatch) { return -1; } } // Check if there are any branch states for the given frame. - if (!BranchStates.ContainsKey(frame) || BranchStates[frame] == null || branchHash == -1) + if (!_branchStates.ContainsKey(frame) || _branchStates[frame] == null || branchHash == -1) { return -2; } // Loop through branch states for the given frame. - SortedList stateList = BranchStates[frame]; + SortedList stateList = _branchStates[frame]; for (int i = 0; i < stateList.Count; i++) { // Don't check the branch containing the state to match. @@ -890,16 +890,16 @@ namespace BizHawk.Client.Common return -2; // No match. } - private Point findState(StateManagerState s) + private Point FindState(StateManagerState s) { Point ret = new Point(0, -1); ret.X = s.Frame; - if (!States.ContainsValue(s)) + if (!_states.ContainsValue(s)) { - if (BranchStates.ContainsKey(s.Frame)) + if (_branchStates.ContainsKey(s.Frame)) { - int index = BranchStates[s.Frame].Values.IndexOf(s); - ret.Y = BranchStates[s.Frame].Keys.ElementAt(index); + int index = _branchStates[s.Frame].Values.IndexOf(s); + ret.Y = _branchStates[s.Frame].Keys.ElementAt(index); } if (ret.Y == -1) @@ -915,19 +915,19 @@ namespace BizHawk.Client.Common { int branchHash = _movie.BranchHashByIndex(_movie.BranchCount - 1); - foreach (KeyValuePair kvp in States) + foreach (KeyValuePair kvp in _states) { - if (!BranchStates.ContainsKey(kvp.Key)) + if (!_branchStates.ContainsKey(kvp.Key)) { - BranchStates.Add(kvp.Key, new SortedList()); + _branchStates.Add(kvp.Key, new SortedList()); } - SortedList stateList = BranchStates[kvp.Key]; + SortedList stateList = _branchStates[kvp.Key]; if (stateList == null) // when does this happen? { stateList = new SortedList(); - BranchStates[kvp.Key] = stateList; + _branchStates[kvp.Key] = stateList; } // We aren't creating any new states, just adding a reference to an already-existing one; so Used doesn't need to be updated. @@ -939,7 +939,7 @@ namespace BizHawk.Client.Common { int branchHash = _movie.BranchHashByIndex(index); - foreach (KeyValuePair> kvp in BranchStates.ToList()) + foreach (KeyValuePair> kvp in _branchStates.ToList()) { SortedList stateList = kvp.Value; if (stateList == null) @@ -960,7 +960,7 @@ namespace BizHawk.Client.Common stateList.Remove(branchHash); if (stateList.Count == 0) { - BranchStates.Remove(kvp.Key); + _branchStates.Remove(kvp.Key); } } } @@ -975,7 +975,7 @@ namespace BizHawk.Client.Common int branchHash = _movie.BranchHashByIndex(index); // RemoveBranch - foreach (KeyValuePair> kvp in BranchStates.ToList()) + foreach (KeyValuePair> kvp in _branchStates.ToList()) { SortedList stateList = kvp.Value; if (stateList == null) @@ -996,24 +996,24 @@ namespace BizHawk.Client.Common stateList.Remove(branchHash); if (stateList.Count == 0) { - BranchStates.Remove(kvp.Key); + _branchStates.Remove(kvp.Key); } } // AddBranch - foreach (KeyValuePair kvp in States) + foreach (KeyValuePair kvp in _states) { - if (!BranchStates.ContainsKey(kvp.Key)) + if (!_branchStates.ContainsKey(kvp.Key)) { - BranchStates.Add(kvp.Key, new SortedList()); + _branchStates.Add(kvp.Key, new SortedList()); } - SortedList stateList = BranchStates[kvp.Key]; + SortedList stateList = _branchStates[kvp.Key]; if (stateList == null) { stateList = new SortedList(); - BranchStates[kvp.Key] = stateList; + _branchStates[kvp.Key] = stateList; } stateList.Add(branchHash, kvp.Value); @@ -1031,9 +1031,9 @@ namespace BizHawk.Client.Common ////Invalidate(0); // Not a good way of doing it? - foreach (KeyValuePair> kvp in BranchStates) + foreach (KeyValuePair> kvp in _branchStates) { - if (kvp.Key == 0 && States.ContainsKey(0)) + if (kvp.Key == 0 && _states.ContainsKey(0)) { continue; // TODO: It might be a better idea to just not put state 0 in BranchStates. } diff --git a/BizHawk.Client.Common/rewind/Rewinder.cs b/BizHawk.Client.Common/rewind/Rewinder.cs index 6a30bdf11d..3f7bbe2704 100644 --- a/BizHawk.Client.Common/rewind/Rewinder.cs +++ b/BizHawk.Client.Common/rewind/Rewinder.cs @@ -253,10 +253,10 @@ namespace BizHawk.Client.Common if (thisByteMatches || i == stateLength - 1) { - const int maxHeaderSize = 10; + const int MaxHeaderSize = 10; int length = i - changeSequenceStartOffset + (thisByteMatches ? 0 : 1); - if (index + length + maxHeaderSize >= stateLength) + if (index + length + MaxHeaderSize >= stateLength) { // If the delta ends up being larger than the full state, capture the full state instead goto CaptureFullState; diff --git a/BizHawk.Client.Common/rewind/StreamBlobDatabase.cs b/BizHawk.Client.Common/rewind/StreamBlobDatabase.cs index de19d0e375..24f7d3637e 100644 --- a/BizHawk.Client.Common/rewind/StreamBlobDatabase.cs +++ b/BizHawk.Client.Common/rewind/StreamBlobDatabase.cs @@ -285,15 +285,15 @@ namespace BizHawk.Client.Common public long EndExclusive => Index + Length; } - private static byte[] test_BufferManage(byte[] inbuf, ref long size, bool allocate) + private static byte[] Test_BufferManage(byte[] inbuf, ref long size, bool allocate) { if (allocate) { // if we have an appropriate buffer free, return it - if (test_rewindFellationBuf != null && test_rewindFellationBuf.LongLength == size) + if (testRewindFellationBuf != null && testRewindFellationBuf.LongLength == size) { - var ret = test_rewindFellationBuf; - test_rewindFellationBuf = null; + var ret = testRewindFellationBuf; + testRewindFellationBuf = null; return ret; } @@ -301,15 +301,15 @@ namespace BizHawk.Client.Common return new byte[size]; } - test_rewindFellationBuf = inbuf; + testRewindFellationBuf = inbuf; return null; } - private static byte[] test_rewindFellationBuf; + private static byte[] testRewindFellationBuf; - private static void test(string[] args) + private static void Test(string[] args) { - var sbb = new StreamBlobDatabase(false, 1024, test_BufferManage); + var sbb = new StreamBlobDatabase(false, 1024, Test_BufferManage); Random r = new Random(0); byte[] temp = new byte[1024]; int trials = 0; diff --git a/BizHawk.Client.Common/tools/CheatList.cs b/BizHawk.Client.Common/tools/CheatList.cs index a14f7197cb..1ec255a96e 100644 --- a/BizHawk.Client.Common/tools/CheatList.cs +++ b/BizHawk.Client.Common/tools/CheatList.cs @@ -13,6 +13,17 @@ namespace BizHawk.Client.Common { public class CheatCollection : ICollection { + private const string NameColumn = "NamesColumn"; + private const string AddressColumn = "AddressColumn"; + private const string ValueColumn = "ValueColumn"; + private const string CompareColumn = "CompareColumn"; + private const string OnColumn = "OnColumn"; + private const string DomainColumn = "DomainColumn"; + private const string SizeColumn = "SizeColumn"; + private const string EndianColumn = "EndianColumn"; + private const string TypeColumn = "DisplayTypeColumn"; + private const string ComparisonType = "ComparisonTypeColumn"; + private List _cheatList = new List(); private string _currentFileName = ""; private string _defaultFileName = ""; @@ -512,7 +523,7 @@ namespace BizHawk.Client.Common { switch (column) { - case NAME: + case NameColumn: if (reverse) { _cheatList = _cheatList @@ -529,7 +540,7 @@ namespace BizHawk.Client.Common } break; - case ADDRESS: + case AddressColumn: if (reverse) { _cheatList = _cheatList @@ -546,7 +557,7 @@ namespace BizHawk.Client.Common } break; - case VALUE: + case ValueColumn: if (reverse) { _cheatList = _cheatList @@ -565,7 +576,7 @@ namespace BizHawk.Client.Common } break; - case COMPARE: + case CompareColumn: if (reverse) { _cheatList = _cheatList @@ -584,7 +595,7 @@ namespace BizHawk.Client.Common } break; - case ON: + case OnColumn: if (reverse) { _cheatList = _cheatList @@ -603,7 +614,7 @@ namespace BizHawk.Client.Common } break; - case DOMAIN: + case DomainColumn: if (reverse) { _cheatList = _cheatList @@ -622,7 +633,7 @@ namespace BizHawk.Client.Common } break; - case SIZE: + case SizeColumn: if (reverse) { _cheatList = _cheatList @@ -641,7 +652,7 @@ namespace BizHawk.Client.Common } break; - case ENDIAN: + case EndianColumn: if (reverse) { _cheatList = _cheatList @@ -660,7 +671,7 @@ namespace BizHawk.Client.Common } break; - case TYPE: + case TypeColumn: if (reverse) { _cheatList = _cheatList @@ -679,7 +690,7 @@ namespace BizHawk.Client.Common } break; - case COMPARISONTYPE: + case ComparisonType: if (reverse) { _cheatList = _cheatList @@ -721,16 +732,5 @@ namespace BizHawk.Client.Common public Cheat Cheat { get; private set; } } - - private const string NAME = "NamesColumn"; - private const string ADDRESS = "AddressColumn"; - private const string VALUE = "ValueColumn"; - private const string COMPARE = "CompareColumn"; - private const string ON = "OnColumn"; - private const string DOMAIN = "DomainColumn"; - private const string SIZE = "SizeColumn"; - private const string ENDIAN = "EndianColumn"; - private const string TYPE = "DisplayTypeColumn"; - private const string COMPARISONTYPE = "ComparisonTypeColumn"; } } diff --git a/BizHawk.Client.EmuHawk/CustomControls/InputRoll.Drawing.cs b/BizHawk.Client.EmuHawk/CustomControls/InputRoll.Drawing.cs index f5c459fb5d..316afb409c 100644 --- a/BizHawk.Client.EmuHawk/CustomControls/InputRoll.Drawing.cs +++ b/BizHawk.Client.EmuHawk/CustomControls/InputRoll.Drawing.cs @@ -10,14 +10,14 @@ namespace BizHawk.Client.EmuHawk { protected override void OnPaint(PaintEventArgs e) { - using (var LCK = Gdi.LockGraphics(e.Graphics)) + using (_gdi.LockGraphics(e.Graphics)) { - Gdi.StartOffScreenBitmap(Width, Height); + _gdi.StartOffScreenBitmap(Width, Height); // White Background - Gdi.SetBrush(Color.White); - Gdi.SetSolidPen(Color.White); - Gdi.FillRectangle(0, 0, Width, Height); + _gdi.SetBrush(Color.White); + _gdi.SetSolidPen(Color.White); + _gdi.FillRectangle(0, 0, Width, Height); // Lag frame calculations SetLagFramesArray(); @@ -26,22 +26,21 @@ namespace BizHawk.Client.EmuHawk if (visibleColumns.Any()) { - DrawColumnBg(e, visibleColumns); DrawColumnText(e, visibleColumns); } - //Background + // Background DrawBg(e, visibleColumns); - //Foreground + // Foreground DrawData(e, visibleColumns); DrawColumnDrag(e); DrawCellDrag(e); - Gdi.CopyToScreen(); - Gdi.EndOffScreenBitmap(); + _gdi.CopyToScreen(); + _gdi.EndOffScreenBitmap(); } } @@ -52,48 +51,42 @@ namespace BizHawk.Client.EmuHawk private void DrawColumnDrag(PaintEventArgs e) { - if (_columnDown != null && _currentX.HasValue && _currentY.HasValue && IsHoveringOnColumnCell) + if (_columnDown != null && _columnDownMoved && _currentX.HasValue && _currentY.HasValue && IsHoveringOnColumnCell) { int x1 = _currentX.Value - (_columnDown.Width.Value / 2); int y1 = _currentY.Value - (CellHeight / 2); int x2 = x1 + _columnDown.Width.Value; int y2 = y1 + CellHeight; - Gdi.SetSolidPen(_backColor); - Gdi.DrawRectangle(x1, y1, x2, y2); - Gdi.PrepDrawString(NormalFont, _foreColor); - Gdi.DrawString(_columnDown.Text, new Point(x1 + CellWidthPadding, y1 + CellHeightPadding)); + _gdi.SetSolidPen(_backColor); + _gdi.DrawRectangle(x1, y1, x2, y2); + _gdi.PrepDrawString(_normalFont, _foreColor); + _gdi.DrawString(_columnDown.Text, new Point(x1 + CellWidthPadding, y1 + CellHeightPadding)); } } private void DrawCellDrag(PaintEventArgs e) { - if (DraggingCell != null) + if (_draggingCell != null) { var text = ""; int offsetX = 0; int offsetY = 0; - if (QueryItemText != null) - { - QueryItemText(DraggingCell.RowIndex.Value, DraggingCell.Column, out text, ref offsetX, ref offsetY); - } + QueryItemText?.Invoke(_draggingCell.RowIndex.Value, _draggingCell.Column, out text, ref offsetX, ref offsetY); Color bgColor = _backColor; - if (QueryItemBkColor != null) - { - QueryItemBkColor(DraggingCell.RowIndex.Value, DraggingCell.Column, ref bgColor); - } + QueryItemBkColor?.Invoke(_draggingCell.RowIndex.Value, _draggingCell.Column, ref bgColor); - int x1 = _currentX.Value - (DraggingCell.Column.Width.Value / 2); + int x1 = _currentX.Value - (_draggingCell.Column.Width.Value / 2); int y1 = _currentY.Value - (CellHeight / 2); - int x2 = x1 + DraggingCell.Column.Width.Value; + int x2 = x1 + _draggingCell.Column.Width.Value; int y2 = y1 + CellHeight; - Gdi.SetBrush(bgColor); - Gdi.FillRectangle(x1, y1, x2 - x1, y2 - y1); - Gdi.PrepDrawString(NormalFont, _foreColor); - Gdi.DrawString(text, new Point(x1 + CellWidthPadding + offsetX, y1 + CellHeightPadding + offsetY)); + _gdi.SetBrush(bgColor); + _gdi.FillRectangle(x1, y1, x2 - x1, y2 - y1); + _gdi.PrepDrawString(_normalFont, _foreColor); + _gdi.DrawString(text, new Point(x1 + CellWidthPadding + offsetX, y1 + CellHeightPadding + offsetY)); } } @@ -101,9 +94,9 @@ namespace BizHawk.Client.EmuHawk { if (HorizontalOrientation) { - int start = -VBar.Value; + int start = -_vBar.Value; - Gdi.PrepDrawString(NormalFont, _foreColor); + _gdi.PrepDrawString(_normalFont, _foreColor); foreach (var column in visibleColumns) { @@ -111,13 +104,13 @@ namespace BizHawk.Client.EmuHawk if (IsHoveringOnColumnCell && column == CurrentCell.Column) { - Gdi.PrepDrawString(NormalFont, SystemColors.HighlightText); - Gdi.DrawString(column.Text, point); - Gdi.PrepDrawString(NormalFont, _foreColor); + _gdi.PrepDrawString(_normalFont, SystemColors.HighlightText); + _gdi.DrawString(column.Text, point); + _gdi.PrepDrawString(_normalFont, _foreColor); } else { - Gdi.DrawString(column.Text, point); + _gdi.DrawString(column.Text, point); } start += CellHeight; @@ -125,21 +118,21 @@ namespace BizHawk.Client.EmuHawk } else { - Gdi.PrepDrawString(NormalFont, _foreColor); + _gdi.PrepDrawString(_normalFont, _foreColor); foreach (var column in visibleColumns) { - var point = new Point(column.Left.Value + 2 * CellWidthPadding - HBar.Value, CellHeightPadding); // TODO: fix this CellPadding issue (2 * CellPadding vs just CellPadding) + var point = new Point(column.Left.Value + 2 * CellWidthPadding - _hBar.Value, CellHeightPadding); // TODO: fix this CellPadding issue (2 * CellPadding vs just CellPadding) if (IsHoveringOnColumnCell && column == CurrentCell.Column) { - Gdi.PrepDrawString(NormalFont, SystemColors.HighlightText); - Gdi.DrawString(column.Text, point); - Gdi.PrepDrawString(NormalFont, _foreColor); + _gdi.PrepDrawString(_normalFont, SystemColors.HighlightText); + _gdi.DrawString(column.Text, point); + _gdi.PrepDrawString(_normalFont, _foreColor); } else { - Gdi.DrawString(column.Text, point); + _gdi.DrawString(column.Text, point); } } } @@ -154,10 +147,10 @@ namespace BizHawk.Client.EmuHawk int startRow = FirstVisibleRow; int range = Math.Min(LastVisibleRow, RowCount - 1) - startRow + 1; - Gdi.PrepDrawString(NormalFont, _foreColor); + _gdi.PrepDrawString(_normalFont, _foreColor); for (int i = 0, f = 0; f < range; i++, f++) { - f += lagFrames[i]; + f += _lagFrames[i]; int LastVisible = LastVisibleColumnIndex; for (int j = FirstVisibleColumn; j <= LastVisible; j++) { @@ -167,16 +160,13 @@ namespace BizHawk.Client.EmuHawk int bitmapOffsetX = 0; int bitmapOffsetY = 0; - if (QueryItemIcon != null) - { - QueryItemIcon(f + startRow, visibleColumns[j], ref image, ref bitmapOffsetX, ref bitmapOffsetY); - } + QueryItemIcon?.Invoke(f + startRow, visibleColumns[j], ref image, ref bitmapOffsetX, ref bitmapOffsetY); if (image != null) { x = RowsToPixels(i) + CellWidthPadding + bitmapOffsetX; y = (j * CellHeight) + (CellHeightPadding * 2) + bitmapOffsetY; - Gdi.DrawBitmap(image, new Point(x, y), true); + _gdi.DrawBitmap(image, new Point(x, y), true); } string text; @@ -185,34 +175,32 @@ namespace BizHawk.Client.EmuHawk QueryItemText(f + startRow, visibleColumns[j], out text, ref strOffsetX, ref strOffsetY); // Center Text - x = RowsToPixels(i) + (CellWidth - text.Length * _charSize.Width) / 2; - y = (j * CellHeight) + CellHeightPadding - VBar.Value; + x = RowsToPixels(i) + ((CellWidth - (text.Length * _charSize.Width)) / 2); + y = (j * CellHeight) + CellHeightPadding - _vBar.Value; var point = new Point(x + strOffsetX, y + strOffsetY); var rePrep = false; - if(j==1) - if (SelectedItems.Contains(new Cell { Column = visibleColumns[j], RowIndex = i + startRow })) + if (j == 1) + if (_selectedItems.Contains(new Cell { Column = visibleColumns[j], RowIndex = i + startRow })) { - Gdi.PrepDrawString(RotatedFont, SystemColors.HighlightText); + _gdi.PrepDrawString(_rotatedFont, SystemColors.HighlightText); rePrep = true; } else if (j == 1) { - //1. not sure about this; 2. repreps may be excess, but if we render one column at a time, we do need to change back after rendering the header + // 1. not sure about this; 2. repreps may be excess, but if we render one column at a time, we do need to change back after rendering the header rePrep = true; - Gdi.PrepDrawString(RotatedFont, _foreColor); + _gdi.PrepDrawString(_rotatedFont, _foreColor); } - - if (!string.IsNullOrWhiteSpace(text)) { - Gdi.DrawString(text, point); + _gdi.DrawString(text, point); } if (rePrep) { - Gdi.PrepDrawString(NormalFont, _foreColor); + _gdi.PrepDrawString(_normalFont, _foreColor); } } } @@ -222,11 +210,11 @@ namespace BizHawk.Client.EmuHawk int startRow = FirstVisibleRow; int range = Math.Min(LastVisibleRow, RowCount - 1) - startRow + 1; - Gdi.PrepDrawString(NormalFont, _foreColor); - int xPadding = CellWidthPadding + 1 - HBar.Value; + _gdi.PrepDrawString(_normalFont, _foreColor); + int xPadding = CellWidthPadding + 1 - _hBar.Value; for (int i = 0, f = 0; f < range; i++, f++) // Vertical { - f += lagFrames[i]; + f += _lagFrames[i]; int LastVisible = LastVisibleColumnIndex; for (int j = FirstVisibleColumn; j <= LastVisible; j++) // Horizontal { @@ -241,33 +229,30 @@ namespace BizHawk.Client.EmuHawk int bitmapOffsetX = 0; int bitmapOffsetY = 0; - if (QueryItemIcon != null) - { - QueryItemIcon(f + startRow, visibleColumns[j], ref image, ref bitmapOffsetX, ref bitmapOffsetY); - } + QueryItemIcon?.Invoke(f + startRow, visibleColumns[j], ref image, ref bitmapOffsetX, ref bitmapOffsetY); if (image != null) { - Gdi.DrawBitmap(image, new Point(point.X + bitmapOffsetX, point.Y + bitmapOffsetY + CellHeightPadding), true); + _gdi.DrawBitmap(image, new Point(point.X + bitmapOffsetX, point.Y + bitmapOffsetY + CellHeightPadding), true); } QueryItemText(f + startRow, visibleColumns[j], out text, ref strOffsetX, ref strOffsetY); bool rePrep = false; - if (SelectedItems.Contains(new Cell { Column = visibleColumns[j], RowIndex = f + startRow })) + if (_selectedItems.Contains(new Cell { Column = visibleColumns[j], RowIndex = f + startRow })) { - Gdi.PrepDrawString(NormalFont, SystemColors.HighlightText); + _gdi.PrepDrawString(_normalFont, SystemColors.HighlightText); rePrep = true; } if (!string.IsNullOrWhiteSpace(text)) { - Gdi.DrawString(text, new Point(point.X + strOffsetX, point.Y + strOffsetY)); + _gdi.DrawString(text, new Point(point.X + strOffsetX, point.Y + strOffsetY)); } if (rePrep) { - Gdi.PrepDrawString(NormalFont, _foreColor); + _gdi.PrepDrawString(_normalFont, _foreColor); } } } @@ -277,25 +262,25 @@ namespace BizHawk.Client.EmuHawk private void DrawColumnBg(PaintEventArgs e, List visibleColumns) { - Gdi.SetBrush(SystemColors.ControlLight); - Gdi.SetSolidPen(Color.Black); + _gdi.SetBrush(SystemColors.ControlLight); + _gdi.SetSolidPen(Color.Black); if (HorizontalOrientation) { - Gdi.FillRectangle(0, 0, ColumnWidth + 1, DrawHeight + 1); - Gdi.Line(0, 0, 0, visibleColumns.Count * CellHeight + 1); - Gdi.Line(ColumnWidth, 0, ColumnWidth, visibleColumns.Count * CellHeight + 1); + _gdi.FillRectangle(0, 0, ColumnWidth + 1, DrawHeight + 1); + _gdi.Line(0, 0, 0, visibleColumns.Count * CellHeight + 1); + _gdi.Line(ColumnWidth, 0, ColumnWidth, visibleColumns.Count * CellHeight + 1); - int start = -VBar.Value; + int start = -_vBar.Value; foreach (var column in visibleColumns) { - Gdi.Line(1, start, ColumnWidth, start); + _gdi.Line(1, start, ColumnWidth, start); start += CellHeight; } if (visibleColumns.Any()) { - Gdi.Line(1, start, ColumnWidth, start); + _gdi.Line(1, start, ColumnWidth, start); } } else @@ -303,36 +288,36 @@ namespace BizHawk.Client.EmuHawk int bottomEdge = RowsToPixels(0); // Gray column box and black line underneath - Gdi.FillRectangle(0, 0, Width + 1, bottomEdge + 1); - Gdi.Line(0, 0, TotalColWidth.Value + 1, 0); - Gdi.Line(0, bottomEdge, TotalColWidth.Value + 1, bottomEdge); + _gdi.FillRectangle(0, 0, Width + 1, bottomEdge + 1); + _gdi.Line(0, 0, TotalColWidth.Value + 1, 0); + _gdi.Line(0, bottomEdge, TotalColWidth.Value + 1, bottomEdge); // Vertical black seperators for (int i = 0; i < visibleColumns.Count; i++) { - int pos = visibleColumns[i].Left.Value - HBar.Value; - Gdi.Line(pos, 0, pos, bottomEdge); + int pos = visibleColumns[i].Left.Value - _hBar.Value; + _gdi.Line(pos, 0, pos, bottomEdge); } // Draw right most line if (visibleColumns.Any()) { - int right = TotalColWidth.Value - HBar.Value; - Gdi.Line(right, 0, right, bottomEdge); + int right = TotalColWidth.Value - _hBar.Value; + _gdi.Line(right, 0, right, bottomEdge); } } // Emphasis foreach (var column in visibleColumns.Where(c => c.Emphasis)) { - Gdi.SetBrush(SystemColors.ActiveBorder); + _gdi.SetBrush(SystemColors.ActiveBorder); if (HorizontalOrientation) { - Gdi.FillRectangle(1, visibleColumns.IndexOf(column) * CellHeight + 1, ColumnWidth - 1, ColumnHeight - 1); + _gdi.FillRectangle(1, visibleColumns.IndexOf(column) * CellHeight + 1, ColumnWidth - 1, ColumnHeight - 1); } else { - Gdi.FillRectangle(column.Left.Value + 1 - HBar.Value, 1, column.Width.Value - 1, ColumnHeight - 1); + _gdi.FillRectangle(column.Left.Value + 1 - _hBar.Value, 1, column.Width.Value - 1, ColumnHeight - 1); } } @@ -350,41 +335,42 @@ namespace BizHawk.Client.EmuHawk if (CurrentCell.Column.Emphasis) { - Gdi.SetBrush(Add(SystemColors.Highlight, 0x00222222)); + _gdi.SetBrush(Add(SystemColors.Highlight, 0x00222222)); } else { - Gdi.SetBrush(SystemColors.Highlight); + _gdi.SetBrush(SystemColors.Highlight); } - Gdi.FillRectangle(1, i * CellHeight + 1, ColumnWidth - 1, ColumnHeight - 1); + _gdi.FillRectangle(1, i * CellHeight + 1, ColumnWidth - 1, ColumnHeight - 1); } } else { - //TODO multiple selected columns + // TODO multiple selected columns for (int i = 0; i < visibleColumns.Count; i++) { if (visibleColumns[i] == CurrentCell.Column) { - //Left of column is to the right of the viewable area or right of column is to the left of the viewable area - if (visibleColumns[i].Left.Value - HBar.Value > Width || visibleColumns[i].Right.Value - HBar.Value < 0) + // Left of column is to the right of the viewable area or right of column is to the left of the viewable area + if (visibleColumns[i].Left.Value - _hBar.Value > Width || visibleColumns[i].Right.Value - _hBar.Value < 0) { continue; } - int left = visibleColumns[i].Left.Value - HBar.Value; - int width = visibleColumns[i].Right.Value - HBar.Value - left; + + int left = visibleColumns[i].Left.Value - _hBar.Value; + int width = visibleColumns[i].Right.Value - _hBar.Value - left; if (CurrentCell.Column.Emphasis) { - Gdi.SetBrush(Add(SystemColors.Highlight, 0x00550000)); + _gdi.SetBrush(Add(SystemColors.Highlight, 0x00550000)); } else { - Gdi.SetBrush(SystemColors.Highlight); + _gdi.SetBrush(SystemColors.Highlight); } - Gdi.FillRectangle(left + 1, 1, width - 1, ColumnHeight - 1); + _gdi.FillRectangle(left + 1, 1, width - 1, ColumnHeight - 1); } } } @@ -395,7 +381,6 @@ namespace BizHawk.Client.EmuHawk /// /// Draw Gridlines and background colors using QueryItemBkColor. /// - /// private void DrawBg(PaintEventArgs e, List visibleColumns) { if (UseCustomBackground && QueryItemBkColor != null) @@ -405,20 +390,20 @@ namespace BizHawk.Client.EmuHawk if (GridLines) { - Gdi.SetSolidPen(SystemColors.ControlLight); + _gdi.SetSolidPen(SystemColors.ControlLight); if (HorizontalOrientation) { // Columns for (int i = 1; i < VisibleRows + 1; i++) { int x = RowsToPixels(i); - Gdi.Line(x, 1, x, DrawHeight); + _gdi.Line(x, 1, x, DrawHeight); } // Rows for (int i = 0; i < visibleColumns.Count + 1; i++) { - Gdi.Line(RowsToPixels(0) + 1, i * CellHeight - VBar.Value, DrawWidth, i * CellHeight - VBar.Value); + _gdi.Line(RowsToPixels(0) + 1, i * CellHeight - _vBar.Value, DrawWidth, i * CellHeight - _vBar.Value); } } else @@ -428,24 +413,24 @@ namespace BizHawk.Client.EmuHawk int? totalColWidth = TotalColWidth; foreach (var column in visibleColumns) { - int x = column.Left.Value - HBar.Value; - Gdi.Line(x, y, x, Height - 1); + int x = column.Left.Value - _hBar.Value; + _gdi.Line(x, y, x, Height - 1); } if (visibleColumns.Any()) { - Gdi.Line(totalColWidth.Value - HBar.Value, y, totalColWidth.Value - HBar.Value, Height - 1); + _gdi.Line(totalColWidth.Value - _hBar.Value, y, totalColWidth.Value - _hBar.Value, Height - 1); } // Rows for (int i = 1; i < VisibleRows + 1; i++) { - Gdi.Line(0, RowsToPixels(i), Width + 1, RowsToPixels(i)); + _gdi.Line(0, RowsToPixels(i), Width + 1, RowsToPixels(i)); } } } - if (SelectedItems.Any()) + if (_selectedItems.Any()) { DoSelectionBG(e, visibleColumns); } @@ -457,11 +442,12 @@ namespace BizHawk.Client.EmuHawk Color rowColor = Color.White; int _lastVisibleRow = LastVisibleRow; int lastRow = -1; - foreach (Cell cell in SelectedItems) + foreach (Cell cell in _selectedItems) { - if (cell.RowIndex > _lastVisibleRow || cell.RowIndex < FirstVisibleRow || - !VisibleColumns.Contains(cell.Column)) + if (cell.RowIndex > _lastVisibleRow || cell.RowIndex < FirstVisibleRow || !VisibleColumns.Contains(cell.Column)) + { continue; + } Cell relativeCell = new Cell { @@ -478,6 +464,7 @@ namespace BizHawk.Client.EmuHawk Color cellColor = rowColor; QueryItemBkColor(cell.RowIndex.Value, cell.Column, ref cellColor); + // Alpha layering for cell before selection float alpha = (float)cellColor.A / 255; if (cellColor.A != 255 && cellColor.A != 0) @@ -486,6 +473,7 @@ namespace BizHawk.Client.EmuHawk rowColor.G - (int)((rowColor.G - cellColor.G) * alpha), rowColor.B - (int)((rowColor.B - cellColor.B) * alpha)); } + // Alpha layering for selection alpha = 0.33f; cellColor = Color.FromArgb(cellColor.R - (int)((cellColor.R - SystemColors.Highlight.R) * alpha), @@ -506,14 +494,17 @@ namespace BizHawk.Client.EmuHawk { x = RowsToPixels(cell.RowIndex.Value) + 1; w = CellWidth - 1; - y = (CellHeight * visibleColumns.IndexOf(cell.Column)) + 1 - VBar.Value; // We can't draw without row and column, so assume they exist and fail catastrophically if they don't + y = (CellHeight * visibleColumns.IndexOf(cell.Column)) + 1 - _vBar.Value; // We can't draw without row and column, so assume they exist and fail catastrophically if they don't h = CellHeight - 1; - if (x < ColumnWidth) { return; } + if (x < ColumnWidth) + { + return; + } } else { w = cell.Column.Width.Value - 1; - x = cell.Column.Left.Value - HBar.Value + 1; + x = cell.Column.Left.Value - _hBar.Value + 1; y = RowsToPixels(cell.RowIndex.Value) + 1; // We can't draw without row and column, so assume they exist and fail catastrophically if they don't h = CellHeight - 1; if (y < ColumnHeight) @@ -527,8 +518,8 @@ namespace BizHawk.Client.EmuHawk return; } // Don't draw if off screen. - Gdi.SetBrush(color); - Gdi.FillRectangle(x, y, w, h); + _gdi.SetBrush(color); + _gdi.FillRectangle(x, y, w, h); } /// @@ -545,13 +536,10 @@ namespace BizHawk.Client.EmuHawk { for (int i = 0, f = 0; f < range; i++, f++) { - f += lagFrames[i]; + f += _lagFrames[i]; Color rowColor = Color.White; - if (QueryRowBkColor != null) - { - QueryRowBkColor(f + startIndex, ref rowColor); - } + QueryRowBkColor?.Invoke(f + startIndex, ref rowColor); for (int j = firstVisibleColumn; j <= lastVisible; j++) { @@ -561,7 +549,6 @@ namespace BizHawk.Client.EmuHawk { itemColor = rowColor; } - else if (itemColor.A != 255 && itemColor.A != 0) { float alpha = (float)itemColor.A / 255; @@ -586,13 +573,10 @@ namespace BizHawk.Client.EmuHawk { for (int i = 0, f = 0; f < range; i++, f++) // Vertical { - f += lagFrames[i]; + f += _lagFrames[i]; Color rowColor = Color.White; - if (QueryRowBkColor != null) - { - QueryRowBkColor(f + startIndex, ref rowColor); - } + QueryRowBkColor?.Invoke(f + startIndex, ref rowColor); for (int j = FirstVisibleColumn; j <= lastVisible; j++) // Horizontal { diff --git a/BizHawk.Client.EmuHawk/CustomControls/InputRoll.cs b/BizHawk.Client.EmuHawk/CustomControls/InputRoll.cs index a09bb32df5..f0ac656f36 100644 --- a/BizHawk.Client.EmuHawk/CustomControls/InputRoll.cs +++ b/BizHawk.Client.EmuHawk/CustomControls/InputRoll.cs @@ -10,16 +10,24 @@ using BizHawk.Client.EmuHawk.CustomControls; namespace BizHawk.Client.EmuHawk { - //Row width depends on font size and padding - //Column width is specified in column headers - //Row width is specified for horizontal orientation + // Row width depends on font size and padding + // Column width is specified in column headers + // Row width is specified for horizontal orientation public partial class InputRoll : Control { - private readonly GDIRenderer Gdi; - private readonly SortedSet SelectedItems = new SortedSet(new sortCell()); + private readonly GDIRenderer _gdi; + private readonly SortedSet _selectedItems = new SortedSet(new SortCell()); - private readonly VScrollBar VBar; - private readonly HScrollBar HBar; + private readonly VScrollBar _vBar; + private readonly HScrollBar _hBar; + + private readonly Timer _hoverTimer = new Timer(); + private readonly byte[] _lagFrames = new byte[256]; // Large enough value that it shouldn't ever need resizing. // apparently not large enough for 4K + + private readonly IntPtr _rotatedFont; + private readonly IntPtr _normalFont; + private readonly Color _foreColor; + private readonly Color _backColor; private RollColumns _columns = new RollColumns(); private bool _horizontalOrientation; @@ -37,16 +45,10 @@ namespace BizHawk.Client.EmuHawk // Hiding lag frames (Mainly intended for < 60fps play.) public int LagFramesToHide { get; set; } public bool HideWasLagFrames { get; set; } - private byte[] lagFrames = new byte[256]; // Large enough value that it shouldn't ever need resizing. // apparently not large enough for 4K - public bool allowRightClickSelecton { get; set; } - public bool letKeysModifySelection { get; set; } - public bool suspendHotkeys { get; set; } - - private IntPtr RotatedFont; - private readonly IntPtr NormalFont; - private Color _foreColor; - private Color _backColor; + public bool AllowRightClickSelecton { get; set; } + public bool LetKeysModifySelection { get; set; } + public bool SuspendHotkeys { get; set; } public InputRoll() { @@ -57,30 +59,31 @@ namespace BizHawk.Client.EmuHawk CurrentCell = null; ScrollMethod = "near"; - Font CommonFont = new Font("Arial", 8, FontStyle.Bold); - NormalFont = GDIRenderer.CreateNormalHFont(CommonFont, 6); + var commonFont = new Font("Arial", 8, FontStyle.Bold); + _normalFont = GDIRenderer.CreateNormalHFont(commonFont, 6); + // PrepDrawString doesn't actually set the font, so this is rather useless. // I'm leaving this stuff as-is so it will be a bit easier to fix up with another rendering method. - RotatedFont = GDIRenderer.CreateRotatedHFont(CommonFont, true); + _rotatedFont = GDIRenderer.CreateRotatedHFont(commonFont, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.SupportsTransparentBackColor, true); SetStyle(ControlStyles.Opaque, true); - Gdi = new GDIRenderer(); + _gdi = new GDIRenderer(); using (var g = CreateGraphics()) - using (var LCK = Gdi.LockGraphics(g)) + using (_gdi.LockGraphics(g)) { - _charSize = Gdi.MeasureString("A", CommonFont); // TODO make this a property so changing it updates other values. + _charSize = _gdi.MeasureString("A", commonFont); // TODO make this a property so changing it updates other values. } UpdateCellSize(); ColumnWidth = CellWidth; ColumnHeight = CellHeight + 2; - VBar = new VScrollBar + _vBar = new VScrollBar { // Location gets calculated later (e.g. on resize) Visible = false, @@ -88,7 +91,7 @@ namespace BizHawk.Client.EmuHawk LargeChange = CellHeight * 20 }; - HBar = new HScrollBar + _hBar = new HScrollBar { // Location gets calculated later (e.g. on resize) Visible = false, @@ -96,11 +99,11 @@ namespace BizHawk.Client.EmuHawk LargeChange = 20 }; - Controls.Add(VBar); - Controls.Add(HBar); + Controls.Add(_vBar); + Controls.Add(_hBar); - VBar.ValueChanged += VerticalBar_ValueChanged; - HBar.ValueChanged += HorizontalBar_ValueChanged; + _vBar.ValueChanged += VerticalBar_ValueChanged; + _hBar.ValueChanged += HorizontalBar_ValueChanged; HorizontalOrientation = false; RecalculateScrollBars(); @@ -118,24 +121,19 @@ namespace BizHawk.Client.EmuHawk { _hoverTimer.Stop(); - if (CellHovered != null) - { - CellHovered(this, new CellEventArgs(LastCell, CurrentCell)); - } + CellHovered?.Invoke(this, new CellEventArgs(LastCell, CurrentCell)); } protected override void Dispose(bool disposing) { - Gdi.Dispose(); + _gdi.Dispose(); - GDIRenderer.DestroyHFont(NormalFont); - GDIRenderer.DestroyHFont(RotatedFont); + GDIRenderer.DestroyHFont(_normalFont); + GDIRenderer.DestroyHFont(_rotatedFont); base.Dispose(disposing); } - private Timer _hoverTimer = new Timer(); - #region Properties /// @@ -153,14 +151,14 @@ namespace BizHawk.Client.EmuHawk public int CellHeightPadding { get; set; } /// - /// Displays grid lines around cells + /// Gets or sets a value indicating whether grid lines are displayed around cells /// [Category("Appearance")] [DefaultValue(true)] public bool GridLines { get; set; } /// - /// Gets or sets whether the control is horizontal or vertical + /// Gets or sets a value indicating whether the control is horizontal or vertical /// [Category("Behavior")] public bool HorizontalOrientation @@ -176,8 +174,8 @@ namespace BizHawk.Client.EmuHawk int temp = ScrollSpeed; _horizontalOrientation = value; OrientationChanged(); - HBar.SmallChange = CellWidth; - VBar.SmallChange = CellHeight; + _hBar.SmallChange = CellWidth; + _vBar.SmallChange = CellHeight; ScrollSpeed = temp; } } @@ -192,16 +190,23 @@ namespace BizHawk.Client.EmuHawk get { if (HorizontalOrientation) - return HBar.SmallChange / CellWidth; - else - return VBar.SmallChange / CellHeight; + { + return _hBar.SmallChange / CellWidth; + } + + return _vBar.SmallChange / CellHeight; } + set { if (HorizontalOrientation) - HBar.SmallChange = value * CellWidth; + { + _hBar.SmallChange = value * CellWidth; + } else - VBar.SmallChange = value * CellHeight; + { + _vBar.SmallChange = value * CellHeight; + } } } @@ -224,33 +229,33 @@ namespace BizHawk.Client.EmuHawk } /// - /// Gets or sets the sets the columns can be resized + /// Gets or sets a value indicating whether columns can be resized /// [Category("Behavior")] public bool AllowColumnResize { get; set; } /// - /// Gets or sets the sets the columns can be reordered + /// Gets or sets a value indicating whether columns can be reordered /// [Category("Behavior")] public bool AllowColumnReorder { get; set; } /// - /// Indicates whether the entire row will always be selected + /// Gets or sets a value indicating whether the entire row will always be selected /// [Category("Appearance")] [DefaultValue(false)] public bool FullRowSelect { get; set; } /// - /// Allows multiple items to be selected + /// Gets or sets a value indicating whether multiple items can to be selected /// [Category("Behavior")] [DefaultValue(true)] public bool MultiSelect { get; set; } /// - /// Gets or sets whether or not the control is in input painting mode + /// Gets or sets a value indicating whether the control is in input painting mode /// [Category("Behavior")] [DefaultValue(false)] @@ -260,7 +265,7 @@ namespace BizHawk.Client.EmuHawk /// All visible columns /// [Category("Behavior")] - public IEnumerable VisibleColumns { get { return _columns.VisibleColumns; } } + public IEnumerable VisibleColumns => _columns.VisibleColumns; /// /// Gets or sets how the InputRoll scrolls when calling ScrollToIndex. @@ -270,7 +275,7 @@ namespace BizHawk.Client.EmuHawk public string ScrollMethod { get; set; } /// - /// Gets or sets how the Intever for the hover event + /// Gets or sets a value indicating how the Intever for the hover event /// [Category("Behavior")] public bool AlwaysScroll { get; set; } @@ -287,8 +292,7 @@ namespace BizHawk.Client.EmuHawk /// [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public RollColumns AllColumns { get { return _columns; } } - + public RollColumns AllColumns => _columns; [DefaultValue(750)] [Category("Behavior")] @@ -303,27 +307,28 @@ namespace BizHawk.Client.EmuHawk #region Event Handlers /// - /// Fire the QueryItemText event which requests the text for the passed cell + /// Fire the event which requests the text for the passed cell /// [Category("Virtual")] public event QueryItemTextHandler QueryItemText; /// - /// Fire the QueryItemBkColor event which requests the background color for the passed cell + /// Fire the event which requests the background color for the passed cell /// [Category("Virtual")] public event QueryItemBkColorHandler QueryItemBkColor; + [Category("Virtual")] public event QueryRowBkColorHandler QueryRowBkColor; /// - /// Fire the QueryItemIconHandler event which requests an icon for a given cell + /// Fire the event which requests an icon for a given cell /// [Category("Virtual")] public event QueryItemIconHandler QueryItemIcon; /// - /// SuuperW: Fire the QueryFrameLag event which checks if a given frame is a lag frame + /// Fire the QueryFrameLag event which checks if a given frame is a lag frame /// [Category("Virtual")] public event QueryFrameLagHandler QueryFrameLag; @@ -392,12 +397,12 @@ namespace BizHawk.Client.EmuHawk public delegate void QueryRowBkColorHandler(int index, ref Color color); /// - /// Retrive the image for a given cell + /// Retrieve the image for a given cell /// - public delegate void QueryItemIconHandler(int index, RollColumn column, ref Bitmap icon, ref int offsetX, ref int offsetY); + public delegate void QueryItemIconHandler(int index, RollColumn column, ref Bitmap icon, ref int offsetX, ref int offsetY); /// - /// SuuperW: Check if a given frame is a lag frame + /// Check if a given frame is a lag frame /// public delegate bool QueryFrameLagHandler(int index, bool hideWasLag); @@ -445,7 +450,7 @@ namespace BizHawk.Client.EmuHawk { Column = column; OldDisplayIndex = oldDisplayIndex; - NewDisplayIndex = NewDisplayIndex; + NewDisplayIndex = newDisplayIndex; } public RollColumn Column { get; private set; } @@ -471,8 +476,8 @@ namespace BizHawk.Client.EmuHawk } else { - IEnumerable items = SelectedItems.Where(cell => cell.RowIndex == index); - SelectedItems.RemoveWhere(items.Contains); + IEnumerable items = _selectedItems.Where(cell => cell.RowIndex == index); + _selectedItems.RemoveWhere(items.Contains); } } } @@ -488,25 +493,20 @@ namespace BizHawk.Client.EmuHawk FullRowSelect = oldFullRowVal; } + public void DeselectAll() { - SelectedItems.Clear(); + _selectedItems.Clear(); } public void TruncateSelection(int index) { - SelectedItems.RemoveWhere(cell => cell.RowIndex > index); + _selectedItems.RemoveWhere(cell => cell.RowIndex > index); } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPointingAtColumnHeader - { - get - { - return IsHoveringOnColumnCell; - } - } + public bool IsPointingAtColumnHeader => IsHoveringOnColumnCell; [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] @@ -539,7 +539,7 @@ namespace BizHawk.Client.EmuHawk } /// - /// The current Cell that the mouse was in. + /// Gets or sets the current Cell that the mouse was in. /// [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] @@ -547,39 +547,33 @@ namespace BizHawk.Client.EmuHawk [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool CurrentCellIsDataCell - { - get - { - return CurrentCell != null && CurrentCell.RowIndex.HasValue && CurrentCell.Column != null; - } - } + public bool CurrentCellIsDataCell => CurrentCell?.RowIndex != null && CurrentCell.Column != null; /// - /// The previous Cell that the mouse was in. + /// Gets or sets the previous Cell that the mouse was in. /// [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - public Cell LastCell { get; set; } + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Cell LastCell { get; private set; } [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - public bool IsPaintDown { get; set; } + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPaintDown { get; private set; } [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool UseCustomBackground { get; set; } [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int DrawHeight { get; private set; } [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int DrawWidth { get; private set; } /// - /// Sets the width of data cells when in Horizontal orientation. + /// Gets or sets the width of data cells when in Horizontal orientation. /// public int MaxCharactersInHorizontal { @@ -596,8 +590,8 @@ namespace BizHawk.Client.EmuHawk } [Browsable(false)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] - public bool RightButtonHeld { get; set; } + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool RightButtonHeld { get; private set; } public string UserSettingsSerialized() { @@ -621,20 +615,13 @@ namespace BizHawk.Client.EmuHawk } } - - private InputRollSettings Settings + private InputRollSettings Settings => new InputRollSettings { - get - { - return new InputRollSettings - { - Columns = _columns, - HorizontalOrientation = HorizontalOrientation, - LagFramesToHide = LagFramesToHide, - HideWasLagFrames = HideWasLagFrames - }; - } - } + Columns = _columns, + HorizontalOrientation = HorizontalOrientation, + LagFramesToHide = LagFramesToHide, + HideWasLagFrames = HideWasLagFrames + }; public class InputRollSettings { @@ -655,10 +642,10 @@ namespace BizHawk.Client.EmuHawk { if (HorizontalOrientation) { - return HBar.Value / CellWidth; + return _hBar.Value / CellWidth; } - return VBar.Value / CellHeight; + return _vBar.Value / CellHeight; } set @@ -668,10 +655,15 @@ namespace BizHawk.Client.EmuHawk if (NeedsHScrollbar) { _programmaticallyUpdatingScrollBarValues = true; - if (value * CellWidth <= HBar.Maximum) - HBar.Value = value * CellWidth; + if (value * CellWidth <= _hBar.Maximum) + { + _hBar.Value = value * CellWidth; + } else - HBar.Value = HBar.Maximum; + { + _hBar.Value = _hBar.Maximum; + } + _programmaticallyUpdatingScrollBarValues = false; } } @@ -680,10 +672,15 @@ namespace BizHawk.Client.EmuHawk if (NeedsVScrollbar) { _programmaticallyUpdatingScrollBarValues = true; - if (value * CellHeight <= VBar.Maximum) - VBar.Value = value * CellHeight; + if (value * CellHeight <= _vBar.Maximum) + { + _vBar.Value = value * CellHeight; + } else - VBar.Value = VBar.Maximum; + { + _vBar.Value = _vBar.Maximum; + } + _programmaticallyUpdatingScrollBarValues = false; } } @@ -696,12 +693,16 @@ namespace BizHawk.Client.EmuHawk { get { - int HalfRow = 0; + int halfRow = 0; if ((DrawHeight - ColumnHeight - 3) % CellHeight < CellHeight / 2) - HalfRow = 1; - return FirstVisibleRow + VisibleRows - HalfRow + CountLagFramesDisplay(VisibleRows - HalfRow); + { + halfRow = 1; + } + + return FirstVisibleRow + VisibleRows - halfRow + CountLagFramesDisplay(VisibleRows - halfRow); } } + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int LastVisibleRow @@ -713,18 +714,21 @@ namespace BizHawk.Client.EmuHawk set { - int HalfRow = 0; + int halfRow = 0; if ((DrawHeight - ColumnHeight - 3) % CellHeight < CellHeight / 2) - HalfRow = 1; + { + halfRow = 1; + } + if (LagFramesToHide == 0) { - FirstVisibleRow = Math.Max(value - (VisibleRows - HalfRow), 0); + FirstVisibleRow = Math.Max(value - (VisibleRows - halfRow), 0); } else { if (Math.Abs(LastFullyVisibleRow - value) > VisibleRows) // Big jump { - FirstVisibleRow = Math.Max(value - (ExpectedDisplayRange() - HalfRow), 0); + FirstVisibleRow = Math.Max(value - (ExpectedDisplayRange() - halfRow), 0); SetLagFramesArray(); } @@ -733,12 +737,18 @@ namespace BizHawk.Client.EmuHawk do { if ((lastVisible - value) / (LagFramesToHide + 1) != 0) + { FirstVisibleRow = Math.Max(FirstVisibleRow - ((lastVisible - value) / (LagFramesToHide + 1)), 0); + } else + { FirstVisibleRow -= Math.Sign(lastVisible - value); + } + SetLagFramesArray(); lastVisible = LastFullyVisibleRow; - } while ((lastVisible - value < 0 || lastVisible - value > lagFrames[VisibleRows - HalfRow]) && FirstVisibleRow != 0); + } + while ((lastVisible - value < 0 || lastVisible - value > _lagFrames[VisibleRows - halfRow]) && FirstVisibleRow != 0); } } } @@ -747,9 +757,10 @@ namespace BizHawk.Client.EmuHawk { return (index >= FirstVisibleRow) && (index <= LastFullyVisibleRow); } + public bool IsPartiallyVisible(int index) { - return (index >= FirstVisibleRow) && (index <= LastVisibleRow); + return index >= FirstVisibleRow && index <= LastVisibleRow; } /// @@ -781,13 +792,11 @@ namespace BizHawk.Client.EmuHawk { if (HorizontalOrientation) { - return VBar.Value / CellHeight; - } - else - { - List columnList = VisibleColumns.ToList(); - return columnList.FindIndex(c => c.Right > HBar.Value); + return _vBar.Value / CellHeight; } + + var columnList = VisibleColumns.ToList(); + return columnList.FindIndex(c => c.Right > _hBar.Value); } } @@ -801,37 +810,38 @@ namespace BizHawk.Client.EmuHawk int ret; if (HorizontalOrientation) { - ret = (VBar.Value + DrawHeight) / CellHeight; + ret = (_vBar.Value + DrawHeight) / CellHeight; if (ret >= columnList.Count) + { ret = columnList.Count - 1; + } } else - ret = columnList.FindLastIndex(c => c.Left <= DrawWidth + HBar.Value); + { + ret = columnList.FindLastIndex(c => c.Left <= DrawWidth + _hBar.Value); + } return ret; } } - private Cell DraggingCell = null; + private Cell _draggingCell; public void DragCurrentCell() { - DraggingCell = CurrentCell; + _draggingCell = CurrentCell; } public void ReleaseCurrentCell() { - if (DraggingCell != null) + if (_draggingCell != null) { - var draggedCell = DraggingCell; - DraggingCell = null; + var draggedCell = _draggingCell; + _draggingCell = null; if (CurrentCell != draggedCell) { - if (CellDropped != null) - { - CellDropped(this, new CellEventArgs(draggedCell, CurrentCell)); - } + CellDropped?.Invoke(this, new CellEventArgs(draggedCell, CurrentCell)); } } } @@ -845,16 +855,23 @@ namespace BizHawk.Client.EmuHawk { MakeIndexVisible(index); } + if (!IsVisible(index) || AlwaysScroll) { if (ScrollMethod == "top") + { FirstVisibleRow = index; + } else if (ScrollMethod == "bottom") + { LastVisibleRow = index; + } else if (ScrollMethod == "center") { if (LagFramesToHide == 0) + { FirstVisibleRow = Math.Max(index - (VisibleRows / 2), 0); + } else { if (Math.Abs(FirstVisibleRow + CountLagFramesDisplay(VisibleRows / 2) - index) > VisibleRows) // Big jump @@ -868,16 +885,23 @@ namespace BizHawk.Client.EmuHawk do { if ((lastVisible - index) / (LagFramesToHide + 1) != 0) + { FirstVisibleRow = Math.Max(FirstVisibleRow - ((lastVisible - index) / (LagFramesToHide + 1)), 0); + } else + { FirstVisibleRow -= Math.Sign(lastVisible - index); + } + SetLagFramesArray(); lastVisible = FirstVisibleRow + CountLagFramesDisplay(VisibleRows / 2); - } while ((lastVisible - index < 0 || lastVisible - index > lagFrames[VisibleRows]) && FirstVisibleRow != 0); + } + while ((lastVisible - index < 0 || lastVisible - index > _lagFrames[VisibleRows]) && FirstVisibleRow != 0); } } } } + /// /// Scrolls so that the given index is visible, if it isn't already; doesn't use scroll settings. /// @@ -886,9 +910,13 @@ namespace BizHawk.Client.EmuHawk if (!IsVisible(index)) { if (FirstVisibleRow > index) + { FirstVisibleRow = index; + } else + { LastVisibleRow = index; + } } } @@ -898,23 +926,24 @@ namespace BizHawk.Client.EmuHawk { get { - return SelectedItems + return _selectedItems .Where(cell => cell.RowIndex.HasValue) .Select(cell => cell.RowIndex.Value) .Distinct(); } } + public bool AnyRowsSelected { get { - return SelectedItems.Any(cell => cell.RowIndex.HasValue); + return _selectedItems.Any(cell => cell.RowIndex.HasValue); } } public void ClearSelectedRows() { - SelectedItems.Clear(); + _selectedItems.Clear(); } public IEnumerable GenerateContextMenuItems() @@ -936,16 +965,13 @@ namespace BizHawk.Client.EmuHawk yield return rotate; } - public string RotateHotkeyStr - { - get { return "Ctrl+Shift+F"; } - } + public string RotateHotkeyStr => "Ctrl+Shift+F"; #endregion #region Mouse and Key Events - private bool _columnDownMoved = false; + private bool _columnDownMoved; protected override void OnMouseMove(MouseEventArgs e) { _currentX = e.X; @@ -957,14 +983,18 @@ namespace BizHawk.Client.EmuHawk } Cell newCell = CalculatePointedCell(_currentX.Value, _currentY.Value); + // SuuperW: Hide lag frames if (QueryFrameLag != null && newCell.RowIndex.HasValue) { newCell.RowIndex += CountLagFramesDisplay(newCell.RowIndex.Value); } + newCell.RowIndex += FirstVisibleRow; if (newCell.RowIndex < 0) + { newCell.RowIndex = 0; + } if (!newCell.Equals(CurrentCell)) { @@ -1021,9 +1051,12 @@ namespace BizHawk.Client.EmuHawk { newCell.RowIndex += CountLagFramesDisplay(newCell.RowIndex.Value); } + newCell.RowIndex += FirstVisibleRow; if (newCell.RowIndex < 0) + { newCell.RowIndex = 0; + } if (!newCell.Equals(CurrentCell)) { @@ -1075,22 +1108,21 @@ namespace BizHawk.Client.EmuHawk } else if (ModifierKeys == Keys.Shift) { - if (SelectedItems.Any()) + if (_selectedItems.Any()) { if (FullRowSelect) { - var selected = SelectedItems.Any(c => c.RowIndex.HasValue && CurrentCell.RowIndex.HasValue && c.RowIndex == CurrentCell.RowIndex); + var selected = _selectedItems.Any(c => c.RowIndex.HasValue && CurrentCell.RowIndex.HasValue && c.RowIndex == CurrentCell.RowIndex); if (!selected) { - var rowIndices = SelectedItems + var rowIndices = _selectedItems .Where(c => c.RowIndex.HasValue) .Select(c => c.RowIndex ?? -1) .Where(c => c >= 0) // Hack to avoid possible Nullable exceptions .Distinct() .ToList(); - var firstIndex = rowIndices.Min(); var lastIndex = rowIndices.Max(); @@ -1149,23 +1181,20 @@ namespace BizHawk.Client.EmuHawk } else { - var hadIndex = SelectedItems.Any(); - SelectedItems.Clear(); + var hadIndex = _selectedItems.Any(); + _selectedItems.Clear(); SelectCell(CurrentCell); } Refresh(); - if (SelectedIndexChanged != null) - { - SelectedIndexChanged(this, new EventArgs()); - } + SelectedIndexChanged?.Invoke(this, new EventArgs()); } } base.OnMouseDown(e); - if (allowRightClickSelecton && e.Button == MouseButtons.Right) + if (AllowRightClickSelecton && e.Button == MouseButtons.Right) { if (!IsHoveringOnColumnCell) { @@ -1243,52 +1272,48 @@ namespace BizHawk.Client.EmuHawk { do { - IncrementScrollBar(HBar, e.Delta < 0); + IncrementScrollBar(_hBar, e.Delta < 0); SetLagFramesFirst(); - } while (lagFrames[0] != 0 && HBar.Value != 0 && HBar.Value != HBar.Maximum); + } + while (_lagFrames[0] != 0 && _hBar.Value != 0 && _hBar.Value != _hBar.Maximum); } else { do { - IncrementScrollBar(VBar, e.Delta < 0); + IncrementScrollBar(_vBar, e.Delta < 0); SetLagFramesFirst(); - } while (lagFrames[0] != 0 && VBar.Value != 0 && VBar.Value != VBar.Maximum); + } + while (_lagFrames[0] != 0 && _vBar.Value != 0 && _vBar.Value != _vBar.Maximum); } if (_currentX != null) - OnMouseMove(new MouseEventArgs(System.Windows.Forms.MouseButtons.None, 0, _currentX.Value, _currentY.Value, 0)); + { + OnMouseMove(new MouseEventArgs(MouseButtons.None, 0, _currentX.Value, _currentY.Value, 0)); + } + Refresh(); } } private void DoRightMouseScroll(object sender, MouseEventArgs e) { - if (RightMouseScrolled != null) - { - RightMouseScrolled(sender, e); - } + RightMouseScrolled?.Invoke(sender, e); } private void ColumnClickEvent(RollColumn column) { - if (ColumnClick != null) - { - ColumnClick(this, new ColumnClickEventArgs(column)); - } + ColumnClick?.Invoke(this, new ColumnClickEventArgs(column)); } private void ColumnRightClickEvent(RollColumn column) { - if (ColumnRightClick != null) - { - ColumnRightClick(this, new ColumnClickEventArgs(column)); - } + ColumnRightClick?.Invoke(this, new ColumnClickEventArgs(column)); } protected override void OnKeyDown(KeyEventArgs e) { - if (!suspendHotkeys) + if (!SuspendHotkeys) { if (e.Control && !e.Alt && e.Shift && e.KeyCode == Keys.F) // Ctrl+Shift+F { @@ -1329,7 +1354,7 @@ namespace BizHawk.Client.EmuHawk } else if (e.Control && !e.Shift && !e.Alt && e.KeyCode == Keys.Up) // Ctrl + Up { - if (SelectedRows.Any() && letKeysModifySelection) + if (SelectedRows.Any() && LetKeysModifySelection) { foreach (var row in SelectedRows.ToList()) { @@ -1340,7 +1365,7 @@ namespace BizHawk.Client.EmuHawk } else if (e.Control && !e.Shift && !e.Alt && e.KeyCode == Keys.Down) // Ctrl + Down { - if (SelectedRows.Any() && letKeysModifySelection) + if (SelectedRows.Any() && LetKeysModifySelection) { foreach (var row in SelectedRows.Reverse().ToList()) { @@ -1351,14 +1376,14 @@ namespace BizHawk.Client.EmuHawk } else if (!e.Control && e.Shift && !e.Alt && e.KeyCode == Keys.Up) // Shift + Up { - if (SelectedRows.Any() && letKeysModifySelection) + if (SelectedRows.Any() && LetKeysModifySelection) { SelectRow(SelectedRows.First() - 1, true); } } else if (!e.Control && e.Shift && !e.Alt && e.KeyCode == Keys.Down) // Shift + Down { - if (SelectedRows.Any() && letKeysModifySelection) + if (SelectedRows.Any() && LetKeysModifySelection) { SelectRow(SelectedRows.Last() + 1, true); } @@ -1400,7 +1425,6 @@ namespace BizHawk.Client.EmuHawk RecalculateScrollBars(); // TODO scroll to correct positions - ColumnChangedCallback(); RecalculateScrollBars(); @@ -1421,7 +1445,7 @@ namespace BizHawk.Client.EmuHawk PointedCellChanged(this, new CellEventArgs(LastCell, CurrentCell)); } - if (CurrentCell != null && CurrentCell.Column != null && CurrentCell.RowIndex.HasValue) + if (CurrentCell?.Column != null && CurrentCell.RowIndex.HasValue) { _hoverTimer.Start(); } @@ -1440,21 +1464,12 @@ namespace BizHawk.Client.EmuHawk if (_horizontalOrientation) { - if (ColumnScroll != null) - { - ColumnScroll(this, e); - } + ColumnScroll?.Invoke(this, e); } else { - if (RowScroll != null) - { - RowScroll(this, e); - } + RowScroll?.Invoke(this, e); } - - if (CurrentCell == null) - return; } private void HorizontalBar_ValueChanged(object sender, EventArgs e) @@ -1466,17 +1481,11 @@ namespace BizHawk.Client.EmuHawk if (_horizontalOrientation) { - if (RowScroll != null) - { - RowScroll(this, e); - } + RowScroll?.Invoke(this, e); } else { - if (ColumnScroll != null) - { - ColumnScroll(this, e); - } + ColumnScroll?.Invoke(this, e); } } @@ -1508,18 +1517,15 @@ namespace BizHawk.Client.EmuHawk var oldIndex = _columns.IndexOf(_columnDown); var newIndex = _columns.IndexOf(CurrentCell.Column); - if (ColumnReordered != null) - { - ColumnReordered(this, new ColumnReorderedEventArgs(oldIndex, newIndex, _columnDown)); - } + ColumnReordered?.Invoke(this, new ColumnReorderedEventArgs(oldIndex, newIndex, _columnDown)); _columns.Remove(_columnDown); _columns.Insert(newIndex, _columnDown); } } - //ScrollBar.Maximum = DesiredValue + ScrollBar.LargeChange - 1 - //See MSDN Page for more information on the dumb ScrollBar.Maximum Property + // ScrollBar.Maximum = DesiredValue + ScrollBar.LargeChange - 1 + // See MSDN Page for more information on the dumb ScrollBar.Maximum Property private void RecalculateScrollBars() { UpdateDrawSize(); @@ -1542,60 +1548,60 @@ namespace BizHawk.Client.EmuHawk { if (HorizontalOrientation) { - VBar.LargeChange = DrawHeight / 2; - HBar.Maximum = Math.Max((VisibleRows - 1) * CellHeight, HBar.Maximum); - HBar.LargeChange = (VisibleRows - 1) * CellHeight; + _vBar.LargeChange = DrawHeight / 2; + _hBar.Maximum = Math.Max((VisibleRows - 1) * CellHeight, _hBar.Maximum); + _hBar.LargeChange = (VisibleRows - 1) * CellHeight; } else { - VBar.Maximum = Math.Max((VisibleRows - 1) * CellHeight, VBar.Maximum); // ScrollBar.Maximum is dumb - VBar.LargeChange = (VisibleRows - 1) * CellHeight; - HBar.LargeChange = DrawWidth / 2; + _vBar.Maximum = Math.Max((VisibleRows - 1) * CellHeight, _vBar.Maximum); // ScrollBar.Maximum is dumb + _vBar.LargeChange = (VisibleRows - 1) * CellHeight; + _hBar.LargeChange = DrawWidth / 2; } } - //Update VBar + // Update VBar if (NeedsVScrollbar) { if (HorizontalOrientation) { - VBar.Maximum = ((columns.Count() * CellHeight) - DrawHeight) + VBar.LargeChange; + _vBar.Maximum = ((columns.Count() * CellHeight) - DrawHeight) + _vBar.LargeChange; } else { - VBar.Maximum = RowsToPixels(RowCount + 1) - (CellHeight * 3) + VBar.LargeChange - 1; + _vBar.Maximum = RowsToPixels(RowCount + 1) - (CellHeight * 3) + _vBar.LargeChange - 1; } - VBar.Location = new Point(Width - VBar.Width, 0); - VBar.Height = Height; - VBar.Visible = true; + _vBar.Location = new Point(Width - _vBar.Width, 0); + _vBar.Height = Height; + _vBar.Visible = true; } else { - VBar.Visible = false; - VBar.Value = 0; + _vBar.Visible = false; + _vBar.Value = 0; } - //Update HBar + // Update HBar if (NeedsHScrollbar) { if (HorizontalOrientation) { - HBar.Maximum = RowsToPixels(RowCount + 1) - (CellHeight * 3) + HBar.LargeChange - 1; + _hBar.Maximum = RowsToPixels(RowCount + 1) - (CellHeight * 3) + _hBar.LargeChange - 1; } else { - HBar.Maximum = TotalColWidth.Value - DrawWidth + HBar.LargeChange; + _hBar.Maximum = TotalColWidth.Value - DrawWidth + _hBar.LargeChange; } - HBar.Location = new Point(0, Height - HBar.Height); - HBar.Width = Width - (NeedsVScrollbar ? (VBar.Width + 1) : 0); - HBar.Visible = true; + _hBar.Location = new Point(0, Height - _hBar.Height); + _hBar.Width = Width - (NeedsVScrollbar ? (_vBar.Width + 1) : 0); + _hBar.Visible = true; } else { - HBar.Visible = false; - HBar.Value = 0; + _hBar.Visible = false; + _hBar.Value = 0; } } @@ -1603,7 +1609,7 @@ namespace BizHawk.Client.EmuHawk { if (NeedsVScrollbar) { - DrawWidth = Width - VBar.Width; + DrawWidth = Width - _vBar.Width; } else { @@ -1611,7 +1617,7 @@ namespace BizHawk.Client.EmuHawk } if (NeedsHScrollbar) { - DrawHeight = Height - HBar.Height; + DrawHeight = Height - _hBar.Height; } else { @@ -1629,27 +1635,27 @@ namespace BizHawk.Client.EmuHawk { if (!MultiSelect) { - SelectedItems.Clear(); + _selectedItems.Clear(); } if (FullRowSelect) { - if (toggle && SelectedItems.Any(x => x.RowIndex.HasValue && x.RowIndex == cell.RowIndex)) + if (toggle && _selectedItems.Any(x => x.RowIndex.HasValue && x.RowIndex == cell.RowIndex)) { - var items = SelectedItems + var items = _selectedItems .Where(x => x.RowIndex.HasValue && x.RowIndex == cell.RowIndex) .ToList(); foreach (var item in items) { - SelectedItems.Remove(item); + _selectedItems.Remove(item); } } else { foreach (var column in _columns) { - SelectedItems.Add(new Cell + _selectedItems.Add(new Cell { RowIndex = cell.RowIndex, Column = column @@ -1659,75 +1665,31 @@ namespace BizHawk.Client.EmuHawk } else { - if (toggle && SelectedItems.Any(x => x.RowIndex.HasValue && x.RowIndex == cell.RowIndex)) + if (toggle && _selectedItems.Any(x => x.RowIndex.HasValue && x.RowIndex == cell.RowIndex)) { - var item = SelectedItems + var item = _selectedItems .FirstOrDefault(x => x.Equals(cell)); if (item != null) { - SelectedItems.Remove(item); + _selectedItems.Remove(item); } } else { - SelectedItems.Add(CurrentCell); + _selectedItems.Add(CurrentCell); } } } } - /// - /// Bool that indicates if CurrentCell is a Column Cell. - /// - public bool IsHoveringOnColumnCell - { - get - { - return CurrentCell != null && - CurrentCell.Column != null && - !CurrentCell.RowIndex.HasValue; - } - } + private bool IsHoveringOnColumnCell => CurrentCell?.Column != null && !CurrentCell.RowIndex.HasValue; - /// - /// Bool that indicates if CurrentCell is a Data Cell. - /// - private bool IsHoveringOnDataCell - { - get - { - return CurrentCell != null && - CurrentCell.Column != null && - CurrentCell.RowIndex.HasValue; - } - } + private bool IsHoveringOnDataCell => CurrentCell?.Column != null && CurrentCell.RowIndex.HasValue; - /// - /// Bool that indicates if CurrentCell is a Column Cell. - /// - private bool WasHoveringOnColumnCell - { - get - { - return LastCell != null && - LastCell.Column != null && - !LastCell.RowIndex.HasValue; - } - } + private bool WasHoveringOnColumnCell => LastCell?.Column != null && !LastCell.RowIndex.HasValue; - /// - /// Bool that indicates if CurrentCell is a Data Cell. - /// - private bool WasHoveringOnDataCell - { - get - { - return LastCell != null && - LastCell.Column != null && - LastCell.RowIndex.HasValue; - } - } + private bool WasHoveringOnDataCell => LastCell?.Column != null && LastCell.RowIndex.HasValue; /// /// Finds the specific cell that contains the (x, y) coordinate. @@ -1748,7 +1710,7 @@ namespace BizHawk.Client.EmuHawk { newCell.RowIndex = PixelsToRows(x); - int colIndex = (y + VBar.Value) / CellHeight; + int colIndex = (y + _vBar.Value) / CellHeight; if (colIndex >= 0 && colIndex < columns.Count) { newCell.Column = columns[colIndex]; @@ -1762,19 +1724,17 @@ namespace BizHawk.Client.EmuHawk } if (!(IsPaintDown || RightButtonHeld) && newCell.RowIndex <= -1) // -2 if we're entering from the top + { newCell.RowIndex = null; + } return newCell; } - /// - /// A boolean that indicates if the InputRoll is too large vertically and requires a vertical scrollbar. - /// + // A boolean that indicates if the InputRoll is too large vertically and requires a vertical scrollbar. private bool NeedsVScrollbar { get; set; } - /// - /// A boolean that indicates if the InputRoll is too large horizontally and requires a horizontal scrollbar. - /// + // A boolean that indicates if the InputRoll is too large horizontally and requires a horizontal scrollbar. private bool NeedsHScrollbar { get; set; } /// @@ -1785,7 +1745,7 @@ namespace BizHawk.Client.EmuHawk /// The new width of the RollColumn object. private int UpdateWidth(RollColumn col) { - col.Width = ((col.Text.Length * _charSize.Width) + (CellWidthPadding * 4)); + col.Width = (col.Text.Length * _charSize.Width) + (CellWidthPadding * 4); return col.Width.Value; } @@ -1801,6 +1761,7 @@ namespace BizHawk.Client.EmuHawk { return _columns.VisibleColumns.Last().Right; } + return null; } } @@ -1814,7 +1775,7 @@ namespace BizHawk.Client.EmuHawk { foreach (RollColumn column in _columns.VisibleColumns) { - if (column.Left.Value - HBar.Value <= x && column.Right.Value - HBar.Value >= x) + if (column.Left.Value - _hBar.Value <= x && column.Right.Value - _hBar.Value >= x) { return column; } @@ -1852,27 +1813,21 @@ namespace BizHawk.Client.EmuHawk return (int)Math.Floor((float)(pixels - ColumnHeight) / CellHeight); } - /// - /// The width of the largest column cell in Horizontal Orientation - /// + // The width of the largest column cell in Horizontal Orientation + private int ColumnWidth { get; set; } - /// - /// The height of a column cell in Vertical Orientation. - /// + // The height of a column cell in Vertical Orientation. private int ColumnHeight { get; set; } - //Cell defaults - /// - /// The width of a cell in Horizontal Orientation. Only can be changed by changing the Font or CellPadding. - /// + // The width of a cell in Horizontal Orientation. Only can be changed by changing the Font or CellPadding. private int CellWidth { get; set; } [Browsable(false)] - public int RowHeight { get { return CellHeight; } } + public int RowHeight => CellHeight; /// - /// The height of a cell in Vertical Orientation. Only can be changed by changing the Font or CellPadding. + /// Gets or sets a value indicating the height of a cell in Vertical Orientation. Only can be changed by changing the Font or CellPadding. /// private int CellHeight { get; set; } @@ -1892,12 +1847,16 @@ namespace BizHawk.Client.EmuHawk { int count = 0; for (int i = 0; i <= relativeIndex; i++) - count += lagFrames[i]; + { + count += _lagFrames[i]; + } return count; } + return 0; } + // Count lag frames between FirstDisplayed and given relative frame index private int CountLagFramesAbsolute(int relativeIndex) { @@ -1905,10 +1864,13 @@ namespace BizHawk.Client.EmuHawk { int count = 0; for (int i = 0; i + count <= relativeIndex; i++) - count += lagFrames[i]; + { + count += _lagFrames[i]; + } return count; } + return 0; } @@ -1917,29 +1879,39 @@ namespace BizHawk.Client.EmuHawk if (QueryFrameLag != null && LagFramesToHide != 0) { bool showNext = false; + // First one needs to check BACKWARDS for lag frame count. SetLagFramesFirst(); - int f = lagFrames[0]; + int f = _lagFrames[0]; if (QueryFrameLag(FirstVisibleRow + f, HideWasLagFrames)) + { showNext = true; + } + for (int i = 1; i <= VisibleRows; i++) { - lagFrames[i] = 0; + _lagFrames[i] = 0; if (!showNext) { - for (; lagFrames[i] < LagFramesToHide; lagFrames[i]++) + for (; _lagFrames[i] < LagFramesToHide; _lagFrames[i]++) { if (!QueryFrameLag(FirstVisibleRow + i + f, HideWasLagFrames)) + { break; + } + f++; } } else { if (!QueryFrameLag(FirstVisibleRow + i + f, HideWasLagFrames)) + { showNext = false; + } } - if (lagFrames[i] == LagFramesToHide && QueryFrameLag(FirstVisibleRow + i + f, HideWasLagFrames)) + + if (_lagFrames[i] == LagFramesToHide && QueryFrameLag(FirstVisibleRow + i + f, HideWasLagFrames)) { showNext = true; } @@ -1949,7 +1921,7 @@ namespace BizHawk.Client.EmuHawk { for (int i = 0; i <= VisibleRows; i++) { - lagFrames[i] = 0; + _lagFrames[i] = 0; } } } @@ -1962,18 +1934,23 @@ namespace BizHawk.Client.EmuHawk do { count++; - } while (QueryFrameLag(FirstVisibleRow - count, HideWasLagFrames) && count <= LagFramesToHide); + } + while (QueryFrameLag(FirstVisibleRow - count, HideWasLagFrames) && count <= LagFramesToHide); count--; + // Count forward int fCount = -1; do { fCount++; - } while (QueryFrameLag(FirstVisibleRow + fCount, HideWasLagFrames) && count + fCount < LagFramesToHide); - lagFrames[0] = (byte)fCount; + } + while (QueryFrameLag(FirstVisibleRow + fCount, HideWasLagFrames) && count + fCount < LagFramesToHide); + _lagFrames[0] = (byte)fCount; } else - lagFrames[0] = 0; + { + _lagFrames[0] = 0; + } } // Number of displayed + hidden frames, if fps is as expected @@ -2010,9 +1987,13 @@ namespace BizHawk.Client.EmuHawk { // no check will make it crash for user too, not sure which way of alarm we prefer. no alarm at all will cause all sorts of subtle bugs if (ChangedCallback == null) + { System.Diagnostics.Debug.Fail("ColumnChangedCallback has died!"); + } else + { ChangedCallback(); + } } // TODO: this shouldn't be exposed. But in order to not expose it, each RollColumn must have a change callback, and all property changes must call it, it is quicker and easier to just call this when needed @@ -2028,6 +2009,7 @@ namespace BizHawk.Client.EmuHawk pos += columns[i].Width.Value; columns[i].Right = pos; } + DoChangeCallback(); } @@ -2159,7 +2141,7 @@ namespace BizHawk.Client.EmuHawk } /// - /// + /// Represents a single cell of the /// public class Cell { @@ -2175,10 +2157,7 @@ namespace BizHawk.Client.EmuHawk RowIndex = cell.RowIndex; } - public bool IsDataCell - { - get { return Column != null && RowIndex.HasValue; } - } + public bool IsDataCell => Column != null && RowIndex.HasValue; public override bool Equals(object obj) { @@ -2197,7 +2176,7 @@ namespace BizHawk.Client.EmuHawk } } - private class sortCell : IComparer + private class SortCell : IComparer { int IComparer.Compare(Cell a, Cell b) { @@ -2212,18 +2191,22 @@ namespace BizHawk.Client.EmuHawk { return c1.Column.Name.CompareTo(c2.Column.Name); } - else - return row; + + return row; } - else - return 1; + + return 1; } - else if (c2.RowIndex.HasValue) + + if (c2.RowIndex.HasValue) + { return -1; - else - return c1.Column.Name.CompareTo(c2.Column.Name); + } + + return c1.Column.Name.CompareTo(c2.Column.Name); } } + #endregion } } diff --git a/BizHawk.Client.EmuHawk/Extensions/CoreExtensions.cs b/BizHawk.Client.EmuHawk/Extensions/CoreExtensions.cs index 822451cdd6..234ba3c611 100644 --- a/BizHawk.Client.EmuHawk/Extensions/CoreExtensions.cs +++ b/BizHawk.Client.EmuHawk/Extensions/CoreExtensions.cs @@ -44,10 +44,6 @@ namespace BizHawk.Client.EmuHawk.CoreExtensions { return Properties.Resources.emu7800; } - else if (core is GBA) - { - return Properties.Resources.meteor; - } else if (core is GPGX) { return Properties.Resources.genplus; diff --git a/BizHawk.Client.EmuHawk/GlobalWin.cs b/BizHawk.Client.EmuHawk/GlobalWin.cs index 757abd40dc..e0137c6e4a 100644 --- a/BizHawk.Client.EmuHawk/GlobalWin.cs +++ b/BizHawk.Client.EmuHawk/GlobalWin.cs @@ -1,6 +1,6 @@ -using BizHawk.Client.Common; -using BizHawk.Bizware.BizwareGL; +using BizHawk.Bizware.BizwareGL; +// ReSharper disable StyleCop.SA1401 namespace BizHawk.Client.EmuHawk { public static class GlobalWin @@ -13,15 +13,13 @@ namespace BizHawk.Client.EmuHawk /// public static IGL GL; - public static GLManager.ContextRef CR_GL; - /// /// The IGL_TK to be used for specifically opengl operations (accessing textures from opengl-based cores) /// public static Bizware.BizwareGL.Drivers.OpenTK.IGL_TK IGL_GL; public static Sound Sound; - public static OSDManager OSD = new OSDManager(); + public static readonly OSDManager OSD = new OSDManager(); public static DisplayManager DisplayManager; public static GLManager GLManager; diff --git a/BizHawk.Client.EmuHawk/MainForm.Designer.cs b/BizHawk.Client.EmuHawk/MainForm.Designer.cs index 61cca7e7df..8624674699 100644 --- a/BizHawk.Client.EmuHawk/MainForm.Designer.cs +++ b/BizHawk.Client.EmuHawk/MainForm.Designer.cs @@ -191,6 +191,7 @@ this.CorebsnesAccuracyMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.Coresnes9xMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gBAWithMGBAToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.Atari7800WithEmu7800MenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem16 = new System.Windows.Forms.ToolStripSeparator(); this.allowGameDBCoreOverridesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); @@ -1228,7 +1229,7 @@ this.EmulationSubMenu.Name = "EmulationSubMenu"; this.EmulationSubMenu.Size = new System.Drawing.Size(65, 17); this.EmulationSubMenu.Text = "&Emulation"; - this.EmulationSubMenu.DropDownOpened += new System.EventHandler(this.emulationToolStripMenuItem_DropDownOpened); + this.EmulationSubMenu.DropDownOpened += new System.EventHandler(this.EmulationMenuItem_DropDownOpened); // // PauseMenuItem // @@ -1360,7 +1361,7 @@ this.DisplayFPSMenuItem.Name = "DisplayFPSMenuItem"; this.DisplayFPSMenuItem.Size = new System.Drawing.Size(187, 22); this.DisplayFPSMenuItem.Text = "Display FPS"; - this.DisplayFPSMenuItem.Click += new System.EventHandler(this.DisplayFPSMenuItem_Click); + this.DisplayFPSMenuItem.Click += new System.EventHandler(this.DisplayFpsMenuItem_Click); // // DisplayFrameCounterMenuItem // @@ -1619,7 +1620,7 @@ this.miUnthrottled.Name = "miUnthrottled"; this.miUnthrottled.Size = new System.Drawing.Size(181, 22); this.miUnthrottled.Text = "Unthrottled"; - this.miUnthrottled.Click += new System.EventHandler(this.miUnthrottled_Click); + this.miUnthrottled.Click += new System.EventHandler(this.UnthrottledMenuItem_Click); // // MinimizeSkippingMenuItem // @@ -1800,6 +1801,7 @@ this.NesInQuickNESMenuItem, this.CoreSNESSubMenu, this.gBAWithMGBAToolStripMenuItem, + this.Atari7800WithEmu7800MenuItem, this.toolStripMenuItem16, this.allowGameDBCoreOverridesToolStripMenuItem, this.toolStripSeparator8, @@ -1815,7 +1817,7 @@ this.GBInSGBMenuItem.Name = "GBInSGBMenuItem"; this.GBInSGBMenuItem.Size = new System.Drawing.Size(223, 22); this.GBInSGBMenuItem.Text = "GB in SGB"; - this.GBInSGBMenuItem.Click += new System.EventHandler(this.GBInSGBMenuItem_Click); + this.GBInSGBMenuItem.Click += new System.EventHandler(this.GbInSgbMenuItem_Click); // // NesInQuickNESMenuItem // @@ -1862,14 +1864,21 @@ this.Coresnes9xMenuItem.Name = "Coresnes9xMenuItem"; this.Coresnes9xMenuItem.Size = new System.Drawing.Size(166, 22); this.Coresnes9xMenuItem.Text = "Snes9x"; - this.Coresnes9xMenuItem.Click += new System.EventHandler(this.Coresnes9xMenuItem_Click); + this.Coresnes9xMenuItem.Click += new System.EventHandler(this.CoreSnes9xMenuItem_Click); // // gBAWithMGBAToolStripMenuItem // this.gBAWithMGBAToolStripMenuItem.Name = "gBAWithMGBAToolStripMenuItem"; this.gBAWithMGBAToolStripMenuItem.Size = new System.Drawing.Size(223, 22); this.gBAWithMGBAToolStripMenuItem.Text = "GBA with mGBA"; - this.gBAWithMGBAToolStripMenuItem.Click += new System.EventHandler(this.gBAWithMGBAToolStripMenuItem_Click); + this.gBAWithMGBAToolStripMenuItem.Click += new System.EventHandler(this.GbaWithmGBAMenuItem_Click); + // + // Atari7800WithEmu7800MenuItem + // + this.Atari7800WithEmu7800MenuItem.Name = "Atari7800WithEmu7800MenuItem"; + this.Atari7800WithEmu7800MenuItem.Size = new System.Drawing.Size(223, 22); + this.Atari7800WithEmu7800MenuItem.Text = "Atari 7800 with Emu7800"; + this.Atari7800WithEmu7800MenuItem.Click += new System.EventHandler(this.Atari7800WithEmu7800MenuItem_Click); // // toolStripMenuItem16 // @@ -1881,7 +1890,7 @@ this.allowGameDBCoreOverridesToolStripMenuItem.Name = "allowGameDBCoreOverridesToolStripMenuItem"; this.allowGameDBCoreOverridesToolStripMenuItem.Size = new System.Drawing.Size(223, 22); this.allowGameDBCoreOverridesToolStripMenuItem.Text = "Follow GameDB Core Overrides"; - this.allowGameDBCoreOverridesToolStripMenuItem.Click += new System.EventHandler(this.allowGameDBCoreOverridesToolStripMenuItem_Click); + this.allowGameDBCoreOverridesToolStripMenuItem.Click += new System.EventHandler(this.AllowGameDBCoreOverridesToolStripMenuItem_Click); // // toolStripSeparator8 // @@ -1901,7 +1910,7 @@ this.setLibretroCoreToolStripMenuItem.Name = "setLibretroCoreToolStripMenuItem"; this.setLibretroCoreToolStripMenuItem.Size = new System.Drawing.Size(223, 22); this.setLibretroCoreToolStripMenuItem.Text = "Set Libretro Core"; - this.setLibretroCoreToolStripMenuItem.Click += new System.EventHandler(this.setLibretroCoreToolStripMenuItem_Click); + this.setLibretroCoreToolStripMenuItem.Click += new System.EventHandler(this.SetLibretroCoreMenuItem_Click); // // toolStripSeparator10 // @@ -2085,7 +2094,7 @@ this.gameSharkConverterToolStripMenuItem.Name = "gameSharkConverterToolStripMenuItem"; this.gameSharkConverterToolStripMenuItem.Size = new System.Drawing.Size(183, 22); this.gameSharkConverterToolStripMenuItem.Text = "Cheat Code Converter"; - this.gameSharkConverterToolStripMenuItem.Click += new System.EventHandler(this.gameSharkConverterToolStripMenuItem_Click); + this.gameSharkConverterToolStripMenuItem.Click += new System.EventHandler(this.CheatCodeConverterMenuItem_Click); // // toolStripSeparator29 // @@ -2098,7 +2107,7 @@ this.MultiDiskBundlerFileMenuItem.Name = "MultiDiskBundlerFileMenuItem"; this.MultiDiskBundlerFileMenuItem.Size = new System.Drawing.Size(183, 22); this.MultiDiskBundlerFileMenuItem.Text = "Multi-disk Bundler"; - this.MultiDiskBundlerFileMenuItem.Click += new System.EventHandler(this.CreateMultigameFileMenuItem_Click); + this.MultiDiskBundlerFileMenuItem.Click += new System.EventHandler(this.MultidiskBundlerMenuItem_Click); // // externalToolToolStripMenuItem // @@ -2121,7 +2130,7 @@ this.batchRunnerToolStripMenuItem.Size = new System.Drawing.Size(183, 22); this.batchRunnerToolStripMenuItem.Text = "Batch Runner"; this.batchRunnerToolStripMenuItem.Visible = false; - this.batchRunnerToolStripMenuItem.Click += new System.EventHandler(this.batchRunnerToolStripMenuItem_Click); + this.batchRunnerToolStripMenuItem.Click += new System.EventHandler(this.BatchRunnerToolStripMenuItem_Click); // // ExperimentalToolsSubMenu // @@ -2138,6 +2147,7 @@ this.AutoHawkMenuItem.Name = "AutoHawkMenuItem"; this.AutoHawkMenuItem.Size = new System.Drawing.Size(148, 22); this.AutoHawkMenuItem.Text = "AutoHawk"; + this.AutoHawkMenuItem.Click += new System.EventHandler(this.AutoHawkMenuItem_Click); // // NewHexEditorMenuItem // @@ -2178,21 +2188,21 @@ this.coreToolStripMenuItem.Name = "coreToolStripMenuItem"; this.coreToolStripMenuItem.Size = new System.Drawing.Size(217, 22); this.coreToolStripMenuItem.Text = "&Core"; - this.coreToolStripMenuItem.DropDownOpened += new System.EventHandler(this.coreToolStripMenuItem_DropDownOpened); + this.coreToolStripMenuItem.DropDownOpened += new System.EventHandler(this.CoreToolStripMenuItem_DropDownOpened); // // quickNESToolStripMenuItem // this.quickNESToolStripMenuItem.Name = "quickNESToolStripMenuItem"; this.quickNESToolStripMenuItem.Size = new System.Drawing.Size(118, 22); this.quickNESToolStripMenuItem.Text = "&QuickNes"; - this.quickNESToolStripMenuItem.Click += new System.EventHandler(this.quickNESToolStripMenuItem_Click); + this.quickNESToolStripMenuItem.Click += new System.EventHandler(this.QuickNesToolStripMenuItem_Click); // // nesHawkToolStripMenuItem // this.nesHawkToolStripMenuItem.Name = "nesHawkToolStripMenuItem"; this.nesHawkToolStripMenuItem.Size = new System.Drawing.Size(118, 22); this.nesHawkToolStripMenuItem.Text = "&NesHawk"; - this.nesHawkToolStripMenuItem.Click += new System.EventHandler(this.nesHawkToolStripMenuItem_Click); + this.nesHawkToolStripMenuItem.Click += new System.EventHandler(this.NesHawkToolStripMenuItem_Click); // // toolStripSeparator34 // @@ -2204,7 +2214,7 @@ this.NESPPUViewerMenuItem.Name = "NESPPUViewerMenuItem"; this.NESPPUViewerMenuItem.Size = new System.Drawing.Size(217, 22); this.NESPPUViewerMenuItem.Text = "&PPU Viewer"; - this.NESPPUViewerMenuItem.Click += new System.EventHandler(this.NESPPUViewerMenuItem_Click); + this.NESPPUViewerMenuItem.Click += new System.EventHandler(this.NesPPUViewerMenuItem_Click); // // NESNametableViewerMenuItem // @@ -2225,7 +2235,7 @@ this.musicRipperToolStripMenuItem.Name = "musicRipperToolStripMenuItem"; this.musicRipperToolStripMenuItem.Size = new System.Drawing.Size(217, 22); this.musicRipperToolStripMenuItem.Text = "Music Ripper"; - this.musicRipperToolStripMenuItem.Click += new System.EventHandler(this.musicRipperToolStripMenuItem_Click); + this.musicRipperToolStripMenuItem.Click += new System.EventHandler(this.MusicRipperMenuItem_Click); // // toolStripSeparator17 // @@ -2261,7 +2271,7 @@ this.VSSettingsMenuItem.Name = "VSSettingsMenuItem"; this.VSSettingsMenuItem.Size = new System.Drawing.Size(217, 22); this.VSSettingsMenuItem.Text = "VS Settings..."; - this.VSSettingsMenuItem.Click += new System.EventHandler(this.VSSettingsMenuItem_Click); + this.VSSettingsMenuItem.Click += new System.EventHandler(this.VsSettingsMenuItem_Click); // // MovieSettingsMenuItem // @@ -2306,28 +2316,28 @@ this.VSInsertCoinP1MenuItem.Name = "VSInsertCoinP1MenuItem"; this.VSInsertCoinP1MenuItem.Size = new System.Drawing.Size(143, 22); this.VSInsertCoinP1MenuItem.Text = "Insert Coin P1"; - this.VSInsertCoinP1MenuItem.Click += new System.EventHandler(this.VSInsertCoinP1MenuItem_Click); + this.VSInsertCoinP1MenuItem.Click += new System.EventHandler(this.VsInsertCoinP1MenuItem_Click); // // VSInsertCoinP2MenuItem // this.VSInsertCoinP2MenuItem.Name = "VSInsertCoinP2MenuItem"; this.VSInsertCoinP2MenuItem.Size = new System.Drawing.Size(143, 22); this.VSInsertCoinP2MenuItem.Text = "Insert Coin P2"; - this.VSInsertCoinP2MenuItem.Click += new System.EventHandler(this.VSInsertCoinP2MenuItem_Click); + this.VSInsertCoinP2MenuItem.Click += new System.EventHandler(this.VsInsertCoinP2MenuItem_Click); // // VSServiceSwitchMenuItem // this.VSServiceSwitchMenuItem.Name = "VSServiceSwitchMenuItem"; this.VSServiceSwitchMenuItem.Size = new System.Drawing.Size(143, 22); this.VSServiceSwitchMenuItem.Text = "Service Switch"; - this.VSServiceSwitchMenuItem.Click += new System.EventHandler(this.VSServiceSwitchMenuItem_Click); + this.VSServiceSwitchMenuItem.Click += new System.EventHandler(this.VsServiceSwitchMenuItem_Click); // // barcodeReaderToolStripMenuItem // this.barcodeReaderToolStripMenuItem.Name = "barcodeReaderToolStripMenuItem"; this.barcodeReaderToolStripMenuItem.Size = new System.Drawing.Size(217, 22); this.barcodeReaderToolStripMenuItem.Text = "Barcode Reader"; - this.barcodeReaderToolStripMenuItem.Click += new System.EventHandler(this.barcodeReaderToolStripMenuItem_Click); + this.barcodeReaderToolStripMenuItem.Click += new System.EventHandler(this.BarcodeReaderMenuItem_Click); // // PCESubMenu // @@ -2361,7 +2371,7 @@ this.PCEGraphicsSettingsMenuItem.Name = "PCEGraphicsSettingsMenuItem"; this.PCEGraphicsSettingsMenuItem.Size = new System.Drawing.Size(240, 22); this.PCEGraphicsSettingsMenuItem.Text = "Graphics Settings"; - this.PCEGraphicsSettingsMenuItem.Click += new System.EventHandler(this.PCEGraphicsSettingsMenuItem_Click); + this.PCEGraphicsSettingsMenuItem.Click += new System.EventHandler(this.PceGraphicsSettingsMenuItem_Click); // // toolStripSeparator32 // @@ -2373,7 +2383,7 @@ this.PCEBGViewerMenuItem.Name = "PCEBGViewerMenuItem"; this.PCEBGViewerMenuItem.Size = new System.Drawing.Size(240, 22); this.PCEBGViewerMenuItem.Text = "&BG Viewer"; - this.PCEBGViewerMenuItem.Click += new System.EventHandler(this.PCEBGViewerMenuItem_Click); + this.PCEBGViewerMenuItem.Click += new System.EventHandler(this.PceBgViewerMenuItem_Click); // // PCEtileViewerToolStripMenuItem // @@ -2387,7 +2397,7 @@ this.PceSoundDebuggerToolStripMenuItem.Name = "PceSoundDebuggerToolStripMenuItem"; this.PceSoundDebuggerToolStripMenuItem.Size = new System.Drawing.Size(240, 22); this.PceSoundDebuggerToolStripMenuItem.Text = "&Sound Debugger"; - this.PceSoundDebuggerToolStripMenuItem.Click += new System.EventHandler(this.PceSoundDebuggerToolStripMenuItem_Click); + this.PceSoundDebuggerToolStripMenuItem.Click += new System.EventHandler(this.PceSoundDebuggerMenuItem_Click); // // toolStripSeparator25 // @@ -2511,14 +2521,14 @@ this.SMSenableBIOSToolStripMenuItem.Name = "SMSenableBIOSToolStripMenuItem"; this.SMSenableBIOSToolStripMenuItem.Size = new System.Drawing.Size(221, 22); this.SMSenableBIOSToolStripMenuItem.Text = "Enable BIOS"; - this.SMSenableBIOSToolStripMenuItem.Click += new System.EventHandler(this.SMS_BIOS_Click); + this.SMSenableBIOSToolStripMenuItem.Click += new System.EventHandler(this.SmsBiosMenuItem_Click); // // SMSEnableFMChipMenuItem // this.SMSEnableFMChipMenuItem.Name = "SMSEnableFMChipMenuItem"; this.SMSEnableFMChipMenuItem.Size = new System.Drawing.Size(221, 22); this.SMSEnableFMChipMenuItem.Text = "&Enable FM Chip"; - this.SMSEnableFMChipMenuItem.Click += new System.EventHandler(this.SMSEnableFMChipMenuItem_Click); + this.SMSEnableFMChipMenuItem.Click += new System.EventHandler(this.SmsEnableFmChipMenuItem_Click); // // SMSOverclockMenuItem // @@ -2651,7 +2661,6 @@ this.AtariSubMenu.Name = "AtariSubMenu"; this.AtariSubMenu.Size = new System.Drawing.Size(42, 17); this.AtariSubMenu.Text = "&Atari"; - this.AtariSubMenu.DropDownOpened += new System.EventHandler(this.AtariSubMenu_DropDownOpened); // // AtariSettingsToolStripMenuItem // @@ -2685,7 +2694,7 @@ this.LoadGBInSGBMenuItem.Name = "LoadGBInSGBMenuItem"; this.LoadGBInSGBMenuItem.Size = new System.Drawing.Size(217, 22); this.LoadGBInSGBMenuItem.Text = "Load GB in SGB"; - this.LoadGBInSGBMenuItem.Click += new System.EventHandler(this.LoadGBInSGBMenuItem_Click); + this.LoadGBInSGBMenuItem.Click += new System.EventHandler(this.LoadGbInSgbMenuItem_Click); // // toolStripSeparator28 // @@ -2697,7 +2706,7 @@ this.GBGPUViewerMenuItem.Name = "GBGPUViewerMenuItem"; this.GBGPUViewerMenuItem.Size = new System.Drawing.Size(217, 22); this.GBGPUViewerMenuItem.Text = "GPU Viewer"; - this.GBGPUViewerMenuItem.Click += new System.EventHandler(this.GBGPUViewerMenuItem_Click); + this.GBGPUViewerMenuItem.Click += new System.EventHandler(this.GbGpuViewerMenuItem_Click); // // GBGameGenieMenuItem // @@ -2732,14 +2741,14 @@ this.GBAmGBAMenuItem.Name = "GBAmGBAMenuItem"; this.GBAmGBAMenuItem.Size = new System.Drawing.Size(120, 22); this.GBAmGBAMenuItem.Text = "mGBA"; - this.GBAmGBAMenuItem.Click += new System.EventHandler(this.GBAmGBAMenuItem_Click); + this.GBAmGBAMenuItem.Click += new System.EventHandler(this.UsemGBAMenuItem_Click); // // GBAVBANextMenuItem // this.GBAVBANextMenuItem.Name = "GBAVBANextMenuItem"; this.GBAVBANextMenuItem.Size = new System.Drawing.Size(120, 22); this.GBAVBANextMenuItem.Text = "&VBA-Next"; - this.GBAVBANextMenuItem.Click += new System.EventHandler(this.GBAVBANextMenuItem_Click); + this.GBAVBANextMenuItem.Click += new System.EventHandler(this.UseVbaNextMenuItem_Click); // // GBAcoresettingsToolStripMenuItem1 // @@ -2914,7 +2923,7 @@ this.SnesGBInSGBMenuItem.Name = "SnesGBInSGBMenuItem"; this.SnesGBInSGBMenuItem.Size = new System.Drawing.Size(217, 22); this.SnesGBInSGBMenuItem.Text = "Load GB in SGB"; - this.SnesGBInSGBMenuItem.Click += new System.EventHandler(this.SnesGBInSGBMenuItem_Click); + this.SnesGBInSGBMenuItem.Click += new System.EventHandler(this.SnesGbInSgbMenuItem_Click); // // SnesGameGenieMenuItem // @@ -3045,7 +3054,7 @@ this.DGBsettingsToolStripMenuItem.Name = "DGBsettingsToolStripMenuItem"; this.DGBsettingsToolStripMenuItem.Size = new System.Drawing.Size(125, 22); this.DGBsettingsToolStripMenuItem.Text = "Settings..."; - this.DGBsettingsToolStripMenuItem.Click += new System.EventHandler(this.DGBsettingsToolStripMenuItem_Click); + this.DGBsettingsToolStripMenuItem.Click += new System.EventHandler(this.DgbSettingsMenuItem_Click); // // GenesisSubMenu // @@ -3070,7 +3079,7 @@ this.GenesisGameGenieECDC.Name = "GenesisGameGenieECDC"; this.GenesisGameGenieECDC.Size = new System.Drawing.Size(217, 22); this.GenesisGameGenieECDC.Text = "&Game Genie Encoder/Decoder"; - this.GenesisGameGenieECDC.Click += new System.EventHandler(this.GenesisGameGenieECDC_Click); + this.GenesisGameGenieECDC.Click += new System.EventHandler(this.GenesisGameGenieEcDc_Click); // // toolStripSeparator26 // @@ -3128,7 +3137,7 @@ this.settingsToolStripMenuItem1.Name = "settingsToolStripMenuItem1"; this.settingsToolStripMenuItem1.Size = new System.Drawing.Size(125, 22); this.settingsToolStripMenuItem1.Text = "&Settings..."; - this.settingsToolStripMenuItem1.Click += new System.EventHandler(this.settingsToolStripMenuItem1_Click_1); + this.settingsToolStripMenuItem1.Click += new System.EventHandler(this.AppleIISettingsMenuItem_Click); // // C64SubMenu // @@ -3168,6 +3177,7 @@ this.IntvSubMenu.Name = "IntvSubMenu"; this.IntvSubMenu.Size = new System.Drawing.Size(39, 17); this.IntvSubMenu.Text = "&Intv"; + this.IntvSubMenu.DropDownOpened += new System.EventHandler(this.IntvSubMenu_DropDownOpened); // // IntVControllerSettingsMenuItem // @@ -3188,7 +3198,7 @@ // preferencesToolStripMenuItem // this.preferencesToolStripMenuItem.Name = "preferencesToolStripMenuItem"; - this.preferencesToolStripMenuItem.Size = new System.Drawing.Size(144, 22); + this.preferencesToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.preferencesToolStripMenuItem.Text = "Preferences..."; this.preferencesToolStripMenuItem.Click += new System.EventHandler(this.preferencesToolStripMenuItem_Click); // @@ -3203,7 +3213,7 @@ // preferencesToolStripMenuItem1 // this.preferencesToolStripMenuItem1.Name = "preferencesToolStripMenuItem1"; - this.preferencesToolStripMenuItem1.Size = new System.Drawing.Size(152, 22); + this.preferencesToolStripMenuItem1.Size = new System.Drawing.Size(144, 22); this.preferencesToolStripMenuItem1.Text = "Preferences..."; this.preferencesToolStripMenuItem1.Click += new System.EventHandler(this.preferencesToolStripMenuItem1_Click); // @@ -3825,7 +3835,7 @@ this.GBInSGBContextMenuItem.Name = "GBInSGBContextMenuItem"; this.GBInSGBContextMenuItem.Size = new System.Drawing.Size(152, 22); this.GBInSGBContextMenuItem.Text = "GB in SGB"; - this.GBInSGBContextMenuItem.Click += new System.EventHandler(this.GBInSGBMenuItem_Click); + this.GBInSGBContextMenuItem.Click += new System.EventHandler(this.GbInSgbMenuItem_Click); // // NesInQuickNESContextMenuItem // @@ -3876,7 +3886,7 @@ this.ClearSRAMContextMenuItem.Name = "ClearSRAMContextMenuItem"; this.ClearSRAMContextMenuItem.Size = new System.Drawing.Size(201, 22); this.ClearSRAMContextMenuItem.Text = "Close and Clear SRAM"; - this.ClearSRAMContextMenuItem.Click += new System.EventHandler(this.ClearSRAMContextMenuItem_Click); + this.ClearSRAMContextMenuItem.Click += new System.EventHandler(this.ClearSramContextMenuItem_Click); // // ShowMenuContextMenuSeparator // @@ -3894,7 +3904,7 @@ // this.timerMouseIdle.Enabled = true; this.timerMouseIdle.Interval = 2000; - this.timerMouseIdle.Tick += new System.EventHandler(this.timerMouseIdle_Tick); + this.timerMouseIdle.Tick += new System.EventHandler(this.TimerMouseIdle_Tick); // // MainForm // @@ -4343,6 +4353,7 @@ private System.Windows.Forms.ToolStripSeparator toolStripSeparator35; private System.Windows.Forms.ToolStripMenuItem C64DisksSubMenu; private System.Windows.Forms.ToolStripSeparator toolStripSeparator36; + private System.Windows.Forms.ToolStripMenuItem Atari7800WithEmu7800MenuItem; private System.Windows.Forms.ToolStripMenuItem sNESToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem preferencesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem virtualBoyToolStripMenuItem; diff --git a/BizHawk.Client.EmuHawk/MainForm.Events.cs b/BizHawk.Client.EmuHawk/MainForm.Events.cs index c19c74d10b..d3ee431eae 100644 --- a/BizHawk.Client.EmuHawk/MainForm.Events.cs +++ b/BizHawk.Client.EmuHawk/MainForm.Events.cs @@ -5,9 +5,10 @@ using System.Windows.Forms; using BizHawk.Emulation.Common; using BizHawk.Emulation.Common.IEmulatorExtensions; +using BizHawk.Emulation.Cores.Atari.A7800Hawk; +using BizHawk.Emulation.Cores.Atari.Atari7800; using BizHawk.Emulation.Cores.Calculators; using BizHawk.Emulation.Cores.ColecoVision; -using BizHawk.Emulation.Cores.Nintendo.Gameboy; using BizHawk.Emulation.Cores.Nintendo.NES; using BizHawk.Emulation.Cores.Nintendo.N64; using BizHawk.Emulation.Cores.Nintendo.SNES; @@ -27,7 +28,7 @@ using BizHawk.Emulation.Cores.Computers.Commodore64; namespace BizHawk.Client.EmuHawk { - partial class MainForm + public partial class MainForm { #region File Menu @@ -51,7 +52,7 @@ namespace BizHawk.Client.EmuHawk SaveRAMSubMenu.Enabled = hasSaveRam; if (SaveRAMSubMenu.Font.Bold != needBold) { - var font = new System.Drawing.Font(SaveRAMSubMenu.Font, needBold ? FontStyle.Bold : FontStyle.Regular); + var font = new Font(SaveRAMSubMenu.Font, needBold ? FontStyle.Bold : FontStyle.Regular); SaveRAMSubMenu.Font = font; } @@ -72,62 +73,52 @@ namespace BizHawk.Client.EmuHawk SaveState0MenuItem.Font = new Font( SaveState0MenuItem.Font.FontFamily, SaveState0MenuItem.Font.Size, - _stateSlots.HasSlot(0) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular - ); + _stateSlots.HasSlot(0) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular); SaveState1MenuItem.Font = new Font( SaveState1MenuItem.Font.FontFamily, SaveState1MenuItem.Font.Size, - _stateSlots.HasSlot(1) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular - ); + _stateSlots.HasSlot(1) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular); SaveState2MenuItem.Font = new Font( SaveState2MenuItem.Font.FontFamily, SaveState2MenuItem.Font.Size, - _stateSlots.HasSlot(2) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular - ); + _stateSlots.HasSlot(2) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular); SaveState3MenuItem.Font = new Font( SaveState3MenuItem.Font.FontFamily, SaveState3MenuItem.Font.Size, - _stateSlots.HasSlot(3) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular - ); + _stateSlots.HasSlot(3) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular); SaveState4MenuItem.Font = new Font( SaveState4MenuItem.Font.FontFamily, SaveState4MenuItem.Font.Size, - _stateSlots.HasSlot(4) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular - ); + _stateSlots.HasSlot(4) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular); SaveState5MenuItem.Font = new Font( SaveState5MenuItem.Font.FontFamily, SaveState5MenuItem.Font.Size, - _stateSlots.HasSlot(5) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular - ); + _stateSlots.HasSlot(5) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular); SaveState6MenuItem.Font = new Font( SaveState6MenuItem.Font.FontFamily, SaveState6MenuItem.Font.Size, - _stateSlots.HasSlot(6) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular - ); + _stateSlots.HasSlot(6) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular); SaveState7MenuItem.Font = new Font( SaveState7MenuItem.Font.FontFamily, SaveState7MenuItem.Font.Size, - _stateSlots.HasSlot(7) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular - ); + _stateSlots.HasSlot(7) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular); SaveState8MenuItem.Font = new Font( SaveState8MenuItem.Font.FontFamily, SaveState8MenuItem.Font.Size, - _stateSlots.HasSlot(8) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular - ); + _stateSlots.HasSlot(8) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular); SaveState9MenuItem.Font = new Font( SaveState9MenuItem.Font.FontFamily, SaveState9MenuItem.Font.Size, - _stateSlots.HasSlot(9) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular - ); + _stateSlots.HasSlot(9) ? (FontStyle.Italic | FontStyle.Bold) : FontStyle.Regular); SaveState1MenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Save State 1"].Bindings; SaveState2MenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Save State 2"].Bindings; @@ -234,6 +225,11 @@ namespace BizHawk.Client.EmuHawk } } + private void FlushSaveRAMSubMenu_DropDownOpened(object sender, EventArgs e) + { + FlushSaveRAMMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Flush SRAM"].Bindings; + } + private void MovieSubMenu_DropDownOpened(object sender, EventArgs e) { FullMovieLoadstatesMenuItem.Enabled = !Global.MovieSession.MultiTrack.IsActive; @@ -315,12 +311,16 @@ namespace BizHawk.Client.EmuHawk { var oac = new OpenAdvancedChooser(this); if (oac.ShowHawkDialog() == DialogResult.Cancel) + { return; + } if (oac.Result == OpenAdvancedChooser.Command.RetroLaunchNoGame) { - var argsNoGame = new LoadRomArgs(); - argsNoGame.OpenAdvanced = new OpenAdvanced_LibretroNoGame(Global.Config.LibretroCore); + var argsNoGame = new LoadRomArgs + { + OpenAdvanced = new OpenAdvanced_LibretroNoGame(Global.Config.LibretroCore) + }; LoadRom("", argsNoGame); return; } @@ -335,12 +335,16 @@ namespace BizHawk.Client.EmuHawk filter = oac.SuggestedExtensionFilter; } else if (oac.Result == OpenAdvancedChooser.Command.ClassicLaunchGame) + { args.OpenAdvanced = new OpenAdvanced_OpenRom(); - else throw new InvalidOperationException("Automatic Alpha Sanitizer"); + } + else + { + throw new InvalidOperationException("Automatic Alpha Sanitizer"); + } - - //----------------- - //CLONE OF CODE FROM OpenRom (mostly) + /*************************/ + /* CLONE OF CODE FROM OpenRom (mostly) */ var ofd = new OpenFileDialog { InitialDirectory = PathManager.GetRomsPath(Emulator.SystemId), @@ -359,9 +363,7 @@ namespace BizHawk.Client.EmuHawk var file = new FileInfo(ofd.FileName); Global.Config.LastRomPath = file.DirectoryName; _lastOpenRomFilter = ofd.FilterIndex; - //----------------- - - + /*************************/ LoadRom(file.FullName, args); } @@ -445,6 +447,11 @@ namespace BizHawk.Client.EmuHawk LoadQuickSave("QuickSave" + Global.Config.SaveSlot); } + private void FlushSaveRAMMenuItem_Click(object sender, EventArgs e) + { + FlushSaveRAM(); + } + private void ReadonlyMenuItem_Click(object sender, EventArgs e) { ToggleReadOnly(); @@ -454,8 +461,9 @@ namespace BizHawk.Client.EmuHawk { if (!Emulator.Attributes().Released) { - var result = MessageBox.Show - (this, "Thanks for using Bizhawk! The emulation core you have selected " + + var result = MessageBox.Show( + this, + "Thanks for using Bizhawk! The emulation core you have selected " + "is currently BETA-status. We appreciate your help in testing Bizhawk. " + "You can record a movie on this core if you'd like to, but expect to " + "encounter bugs and sync problems. Continue?", "BizHawk", MessageBoxButtons.YesNo); @@ -582,7 +590,10 @@ namespace BizHawk.Client.EmuHawk private void StopMovieWithoutSavingMenuItem_Click(object sender, EventArgs e) { if (Global.Config.EnableBackupMovies) + { Global.MovieSession.Movie.SaveBackup(); + } + StopMovie(saveChanges: false); } @@ -702,7 +713,7 @@ namespace BizHawk.Client.EmuHawk #region Emulation Menu - private void emulationToolStripMenuItem_DropDownOpened(object sender, EventArgs e) + private void EmulationMenuItem_DropDownOpened(object sender, EventArgs e) { PauseMenuItem.Checked = _didMenuPause ? _wasPaused : EmulatorPaused; @@ -786,12 +797,24 @@ namespace BizHawk.Client.EmuHawk switch (Global.Config.TargetZoomFactors[Emulator.SystemId]) { - case 1: x1MenuItem.Checked = true; break; - case 2: x2MenuItem.Checked = true; break; - case 3: x3MenuItem.Checked = true; break; - case 4: x4MenuItem.Checked = true; break; - case 5: x5MenuItem.Checked = true; break; - case 10: mzMenuItem.Checked = true; break; + case 1: + x1MenuItem.Checked = true; + break; + case 2: + x2MenuItem.Checked = true; + break; + case 3: + x3MenuItem.Checked = true; + break; + case 4: + x4MenuItem.Checked = true; + break; + case 5: + x5MenuItem.Checked = true; + break; + case 10: + mzMenuItem.Checked = true; + break; } } @@ -812,9 +835,9 @@ namespace BizHawk.Client.EmuHawk ToggleFullscreen(); } - private void DisplayFPSMenuItem_Click(object sender, EventArgs e) + private void DisplayFpsMenuItem_Click(object sender, EventArgs e) { - ToggleFPS(); + ToggleFps(); } private void DisplayFrameCounterMenuItem_Click(object sender, EventArgs e) @@ -848,14 +871,9 @@ namespace BizHawk.Client.EmuHawk SetStatusBar(); } - private void SetStatusBar() + private void DisplayMessagesMenuItem_Click(object sender, EventArgs e) { - if (!_inFullscreen) - { - MainStatusBar.Visible = Global.Config.DispChrome_StatusBarWindowed; - PerformLayout(); - FrameBufferResized(); - } + Global.Config.DisplayMessages ^= true; } private void DisplayLogWindowMenuItem_Click(object sender, EventArgs e) @@ -898,7 +916,11 @@ namespace BizHawk.Client.EmuHawk Frameskip8MenuItem.Checked = Global.Config.FrameSkip == 8; Frameskip9MenuItem.Checked = Global.Config.FrameSkip == 9; MinimizeSkippingMenuItem.Enabled = !NeverSkipMenuItem.Checked; - if (!MinimizeSkippingMenuItem.Enabled) MinimizeSkippingMenuItem.Checked = true; + if (!MinimizeSkippingMenuItem.Enabled) + { + MinimizeSkippingMenuItem.Checked = true; + } + AudioThrottleMenuItem.Enabled = Global.Config.SoundEnabled; AudioThrottleMenuItem.Checked = Global.Config.SoundThrottle; VsyncEnabledMenuItem.Checked = Global.Config.VSync; @@ -950,6 +972,12 @@ namespace BizHawk.Client.EmuHawk } } + private void CoreToolStripMenuItem_DropDownOpened(object sender, EventArgs e) + { + quickNESToolStripMenuItem.Checked = Global.Config.NES_InQuickNES; + nesHawkToolStripMenuItem.Checked = !Global.Config.NES_InQuickNES; + } + private void ControllersMenuItem_Click(object sender, EventArgs e) { var controller = new ControllerConfig(Emulator.ControllerDefinition); @@ -973,7 +1001,7 @@ namespace BizHawk.Client.EmuHawk { if (e is RomLoader.RomErrorArgs) { - var args = e as RomLoader.RomErrorArgs; + var args = (RomLoader.RomErrorArgs)e; var result = new FirmwaresConfig(true, args.RomPath).ShowDialog(); args.Retry = result == DialogResult.Retry; } @@ -1026,8 +1054,9 @@ namespace BizHawk.Client.EmuHawk if (new ProfileConfig().ShowDialog() == DialogResult.OK) { GlobalWin.OSD.AddMessage("Profile settings saved"); - //We hide the FirstBoot items since the user setup a Profile - //Is it a bad thing to do this constantly? + + // We hide the FirstBoot items since the user setup a Profile + // Is it a bad thing to do this constantly? Global.Config.FirstBoot = false; ProfileFirstBootLabel.Visible = false; } @@ -1048,6 +1077,7 @@ namespace BizHawk.Client.EmuHawk { RewireSound(); } + old = Global.Config.VSyncThrottle; Global.Config.VSyncThrottle = false; if (old) @@ -1112,6 +1142,12 @@ namespace BizHawk.Client.EmuHawk VsyncMessage(); } + private void UnthrottledMenuItem_Click(object sender, EventArgs e) + { + _unthrottled ^= true; + ThrottleMessage(); + } + private void MinimizeSkippingMenuItem_Click(object sender, EventArgs e) { Global.Config.AutoMinimizeSkipping ^= true; @@ -1153,7 +1189,7 @@ namespace BizHawk.Client.EmuHawk UpdateKeyPriorityIcon(); } - private void GBInSGBMenuItem_Click(object sender, EventArgs e) + private void GbInSgbMenuItem_Click(object sender, EventArgs e) { Global.Config.GB_AsSGB ^= true; @@ -1178,6 +1214,7 @@ namespace BizHawk.Client.EmuHawk GBInSGBMenuItem.Checked = Global.Config.GB_AsSGB; NesInQuickNESMenuItem.Checked = Global.Config.NES_InQuickNES; gBAWithMGBAToolStripMenuItem.Checked = Global.Config.GBA_UsemGBA; + Atari7800WithEmu7800MenuItem.Checked = Global.Config.A78_UseEmu7800; allowGameDBCoreOverridesToolStripMenuItem.Checked = Global.Config.CoreForcingViaGameDB; } @@ -1186,11 +1223,8 @@ namespace BizHawk.Client.EmuHawk Coresnes9xMenuItem.Checked = Global.Config.SNES_InSnes9x; Coresnes9xMenuItem.Visible = VersionInfo.DeveloperBuild; - LibsnesCore.SnesSyncSettings sss = (LibsnesCore.SnesSyncSettings)Global.Config.GetCoreSyncSettings(); - if (sss == null) - { - sss = new LibsnesCore.SnesSyncSettings(); - } + LibsnesCore.SnesSyncSettings sss = (LibsnesCore.SnesSyncSettings)Global.Config.GetCoreSyncSettings() + ?? new LibsnesCore.SnesSyncSettings(); CorebsnesPerformanceMenuItem.Checked = sss.Profile == "Performance"; CorebsnesCompatibilityMenuItem.Checked = sss.Profile == "Compatibility"; @@ -1198,11 +1232,8 @@ namespace BizHawk.Client.EmuHawk private void CorebsnesPerformanceMenuItem_Click(object sender, EventArgs e) { - LibsnesCore.SnesSyncSettings sss = (LibsnesCore.SnesSyncSettings)Global.Config.GetCoreSyncSettings(); - if (sss == null) - { - sss = new LibsnesCore.SnesSyncSettings(); - } + LibsnesCore.SnesSyncSettings sss = (LibsnesCore.SnesSyncSettings)Global.Config.GetCoreSyncSettings() + ?? new LibsnesCore.SnesSyncSettings(); string orig = sss.Profile; @@ -1217,11 +1248,8 @@ namespace BizHawk.Client.EmuHawk private void CorebsnesCompatibilityMenuItem_Click(object sender, EventArgs e) { - LibsnesCore.SnesSyncSettings sss = (LibsnesCore.SnesSyncSettings)Global.Config.GetCoreSyncSettings(); - if (sss == null) - { - sss = new LibsnesCore.SnesSyncSettings(); - } + LibsnesCore.SnesSyncSettings sss = (LibsnesCore.SnesSyncSettings)Global.Config.GetCoreSyncSettings() + ?? new LibsnesCore.SnesSyncSettings(); string orig = sss.Profile; @@ -1234,7 +1262,7 @@ namespace BizHawk.Client.EmuHawk } } - private void Coresnes9xMenuItem_Click(object sender, EventArgs e) + private void CoreSnes9xMenuItem_Click(object sender, EventArgs e) { Global.Config.SNES_InSnes9x ^= true; @@ -1244,11 +1272,30 @@ namespace BizHawk.Client.EmuHawk } } + private void Atari7800WithEmu7800MenuItem_Click(object sender, EventArgs e) + { + Global.Config.A78_UseEmu7800 ^= true; + if (Emulator is A7800Hawk || Emulator is Atari7800) + { + FlagNeedsReboot(); + } + } + + private void AllowGameDBCoreOverridesToolStripMenuItem_Click(object sender, EventArgs e) + { + Global.Config.CoreForcingViaGameDB ^= true; + } + private void N64VideoPluginSettingsMenuItem_Click(object sender, EventArgs e) { N64PluginSettingsMenuItem_Click(sender, e); } + private void SetLibretroCoreMenuItem_Click(object sender, EventArgs e) + { + RunLibretroCoreChooser(); + } + private void SaveConfigMenuItem_Click(object sender, EventArgs e) { SaveConfig(); @@ -1277,7 +1324,8 @@ namespace BizHawk.Client.EmuHawk { Global.Config = ConfigService.Load(PathManager.DefaultIniPath); Global.Config.ResolveDefaults(); - GlobalWin.OSD.AddMessage("Config file loaded"); + InitControls(); //rebind hotkeys + GlobalWin.OSD.AddMessage("Config file loaded: " + PathManager.DefaultIniPath); } private void LoadConfigFromMenuItem_Click(object sender, EventArgs e) @@ -1295,50 +1343,11 @@ namespace BizHawk.Client.EmuHawk { Global.Config = ConfigService.Load(ofd.FileName); Global.Config.ResolveDefaults(); - GlobalWin.OSD.AddMessage("Config file loaded"); + InitControls(); //rebind hotkeys + GlobalWin.OSD.AddMessage("Config file loaded: " + ofd.FileName); } } - private void miUnthrottled_Click(object sender, EventArgs e) - { - _unthrottled ^= true; - ThrottleMessage(); - } - - public bool RunLibretroCoreChooser() - { - var ofd = new OpenFileDialog(); - - if (Global.Config.LibretroCore != null) - { - ofd.FileName = Path.GetFileName(Global.Config.LibretroCore); - ofd.InitialDirectory = Path.GetDirectoryName(Global.Config.LibretroCore); - } - else - { - ofd.InitialDirectory = PathManager.GetPathType("Libretro", "Cores"); - if (!Directory.Exists(ofd.InitialDirectory)) - { - Directory.CreateDirectory(ofd.InitialDirectory); - } - } - - ofd.RestoreDirectory = true; - ofd.Filter = "Libretro Cores (*.dll)|*.dll"; - - if (ofd.ShowDialog() == DialogResult.Cancel) - return false; - - Global.Config.LibretroCore = ofd.FileName; - - return true; - } - - private void setLibretroCoreToolStripMenuItem_Click(object sender, EventArgs e) - { - RunLibretroCoreChooser(); - } - #endregion #region Tools @@ -1379,9 +1388,9 @@ namespace BizHawk.Client.EmuHawk { externalToolToolStripMenuItem.DropDownItems.Clear(); - foreach(ToolStripMenuItem item in ExternalToolManager.ToolStripMenu) + foreach (ToolStripMenuItem item in ExternalToolManager.ToolStripMenu) { - if(item.Enabled) + if (item.Enabled) { item.Click += delegate { @@ -1392,6 +1401,7 @@ namespace BizHawk.Client.EmuHawk { item.Image = Properties.Resources.ExclamationRed; } + externalToolToolStripMenuItem.DropDownItems.Add(item); } @@ -1407,11 +1417,6 @@ namespace BizHawk.Client.EmuHawk NewHexEditorMenuItem.Enabled = GlobalWin.Tools.IsAvailable(); } - private void AutoHawkMenuItem_Click(object sender, EventArgs e) - { - GlobalWin.Tools.Load(); - } - private void ToolBoxMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); @@ -1427,6 +1432,22 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Tools.Load(); } + private void LuaConsoleMenuItem_Click(object sender, EventArgs e) + { + OpenLuaConsole(); + } + + private void TAStudioMenuItem_Click(object sender, EventArgs e) + { + if (!Emulator.CanPollInput()) + { + MessageBox.Show("Current core does not support input polling. TAStudio can't be used."); + return; + } + + GlobalWin.Tools.Load(); + } + private void HexEditorMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); @@ -1442,14 +1463,9 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Tools.Load(); } - private void TAStudioMenuItem_Click(object sender, EventArgs e) + private void CodeDataLoggerMenuItem_Click(object sender, EventArgs e) { - if (!Emulator.CanPollInput()) - { - MessageBox.Show("Current core does not support input polling. TAStudio can't be used."); - return; - } - GlobalWin.Tools.Load(); + GlobalWin.Tools.Load(); } private void MacroToolMenuItem_Click(object sender, EventArgs e) @@ -1462,21 +1478,36 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Tools.Load(); } + private void BasicBotMenuItem_Click(object sender, EventArgs e) + { + GlobalWin.Tools.Load(); + } + private void CheatsMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); } - private void LuaConsoleMenuItem_Click(object sender, EventArgs e) + private void CheatCodeConverterMenuItem_Click(object sender, EventArgs e) { - OpenLuaConsole(); + GlobalWin.Tools.Load(); } - private void batchRunnerToolStripMenuItem_Click(object sender, EventArgs e) + private void MultidiskBundlerMenuItem_Click(object sender, EventArgs e) + { + GlobalWin.Tools.Load(); + } + + private void BatchRunnerToolStripMenuItem_Click(object sender, EventArgs e) { new BatchRun().ShowDialog(); } + private void AutoHawkMenuItem_Click(object sender, EventArgs e) + { + GlobalWin.Tools.Load(); + } + private void NewHexEditorMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); @@ -1486,13 +1517,13 @@ namespace BizHawk.Client.EmuHawk #region NES - private void quickNESToolStripMenuItem_Click(object sender, EventArgs e) + private void QuickNesToolStripMenuItem_Click(object sender, EventArgs e) { Global.Config.NES_InQuickNES = true; FlagNeedsReboot(); } - private void nesHawkToolStripMenuItem_Click(object sender, EventArgs e) + private void NesHawkToolStripMenuItem_Click(object sender, EventArgs e) { Global.Config.NES_InQuickNES = false; FlagNeedsReboot(); @@ -1505,7 +1536,7 @@ namespace BizHawk.Client.EmuHawk VSControlsMenuItem.Enabled = VSSettingsMenuItem.Enabled = - ((Emulator is NES) && (Emulator as NES).IsVS); + Emulator is NES && ((NES)Emulator).IsVS; NESSoundChannelsMenuItem.Enabled = GlobalWin.Tools.IsAvailable(); MovieSettingsMenuItem.Enabled = Emulator is NES && !Global.MovieSession.Movie.IsActive; @@ -1538,7 +1569,7 @@ namespace BizHawk.Client.EmuHawk } } - private void NESPPUViewerMenuItem_Click(object sender, EventArgs e) + private void NesPPUViewerMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); } @@ -1548,7 +1579,7 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Tools.Load(); } - private void musicRipperToolStripMenuItem_Click(object sender, EventArgs e) + private void MusicRipperMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); } @@ -1561,9 +1592,13 @@ namespace BizHawk.Client.EmuHawk private void NESGraphicSettingsMenuItem_Click(object sender, EventArgs e) { if (Emulator is NES) + { new NESGraphicsConfig().ShowDialog(this); + } else if (Emulator is QuickNES) + { new QuickNesConfig().ShowDialog(this); + } } private void NESSoundChannelsMenuItem_Click(object sender, EventArgs e) @@ -1571,9 +1606,9 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Tools.Load(); } - private void VSSettingsMenuItem_Click(object sender, EventArgs e) + private void VsSettingsMenuItem_Click(object sender, EventArgs e) { - if (Emulator is NES && (Emulator as NES).IsVS) + if (Emulator is NES && ((NES)Emulator).IsVS) { new NESVSSettings().ShowHawkDialog(); } @@ -1588,9 +1623,9 @@ namespace BizHawk.Client.EmuHawk } } - private void VSInsertCoinP1MenuItem_Click(object sender, EventArgs e) + private void VsInsertCoinP1MenuItem_Click(object sender, EventArgs e) { - if (Emulator is NES && (Emulator as NES).IsVS) + if (Emulator is NES && ((NES)Emulator).IsVS) { if (!Global.MovieSession.Movie.IsPlaying || Global.MovieSession.Movie.IsFinished) { @@ -1600,9 +1635,9 @@ namespace BizHawk.Client.EmuHawk } } - private void VSInsertCoinP2MenuItem_Click(object sender, EventArgs e) + private void VsInsertCoinP2MenuItem_Click(object sender, EventArgs e) { - if (Emulator is NES && (Emulator as NES).IsVS) + if (Emulator is NES && ((NES)Emulator).IsVS) { if (!Global.MovieSession.Movie.IsPlaying || Global.MovieSession.Movie.IsFinished) { @@ -1612,9 +1647,9 @@ namespace BizHawk.Client.EmuHawk } } - private void VSServiceSwitchMenuItem_Click(object sender, EventArgs e) + private void VsServiceSwitchMenuItem_Click(object sender, EventArgs e) { - if (Emulator is NES && (Emulator as NES).IsVS) + if (Emulator is NES && ((NES)Emulator).IsVS) { if (!Global.MovieSession.Movie.IsPlaying || Global.MovieSession.Movie.IsFinished) { @@ -1627,9 +1662,13 @@ namespace BizHawk.Client.EmuHawk private void NesControllerSettingsMenuItem_Click(object sender, EventArgs e) { if (Emulator is NES) + { new NesControllerSettings().ShowDialog(); + } else if (Emulator is QuickNES) + { GenericCoreConfig.DoDialog(this, "QuickNES Controller Settings", true, false); + } } private void MovieSettingsMenuItem_Click(object sender, EventArgs e) @@ -1640,7 +1679,7 @@ namespace BizHawk.Client.EmuHawk } } - private void barcodeReaderToolStripMenuItem_Click(object sender, EventArgs e) + private void BarcodeReaderMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); } @@ -1668,12 +1707,12 @@ namespace BizHawk.Client.EmuHawk } } - private void PCEGraphicsSettingsMenuItem_Click(object sender, EventArgs e) + private void PceGraphicsSettingsMenuItem_Click(object sender, EventArgs e) { new PCEGraphicsConfig().ShowDialog(); } - private void PCEBGViewerMenuItem_Click(object sender, EventArgs e) + private void PceBgViewerMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); } @@ -1683,16 +1722,11 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Tools.Load(); } - private void PceSoundDebuggerToolStripMenuItem_Click(object sender, EventArgs e) + private void PceSoundDebuggerMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); } - private void CodeDataLoggerMenuItem_Click(object sender, EventArgs e) - { - GlobalWin.Tools.Load(); - } - private void PCEAlwaysPerformSpriteLimitMenuItem_Click(object sender, EventArgs e) { var s = ((PCEngine)Emulator).GetSettings(); @@ -1802,14 +1836,14 @@ namespace BizHawk.Client.EmuHawk PutCoreSyncSettings(ss); } - private void SMS_BIOS_Click(object sender, EventArgs e) + private void SmsBiosMenuItem_Click(object sender, EventArgs e) { var ss = ((SMS)Emulator).GetSyncSettings(); ss.UseBIOS ^= true; PutCoreSyncSettings(ss); } - private void SMSEnableFMChipMenuItem_Click(object sender, EventArgs e) + private void SmsEnableFmChipMenuItem_Click(object sender, EventArgs e) { var ss = ((SMS)Emulator).GetSyncSettings(); ss.EnableFM ^= true; @@ -1901,6 +1935,7 @@ namespace BizHawk.Client.EmuHawk private void LoadTIFileMenuItem_Click(object sender, EventArgs e) { + var ti83 = (TI83)Emulator; var ofd = new OpenFileDialog { InitialDirectory = PathManager.GetRomsPath(Emulator.SystemId), @@ -1912,15 +1947,15 @@ namespace BizHawk.Client.EmuHawk { try { - (Emulator as TI83).LinkPort.SendFileToCalc(File.OpenRead(ofd.FileName), true); + ti83.LinkPort.SendFileToCalc(File.OpenRead(ofd.FileName), true); } catch (IOException ex) { - var Message = String.Format("Invalid file format. Reason: {0} \nForce transfer? This may cause the calculator to crash.", ex.Message); + var message = $"Invalid file format. Reason: {ex.Message} \nForce transfer? This may cause the calculator to crash."; - if (MessageBox.Show(Message, "Upload Failed", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes) + if (MessageBox.Show(message, "Upload Failed", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes) { - (Emulator as TI83).LinkPort.SendFileToCalc(File.OpenRead(ofd.FileName), false); + ti83.LinkPort.SendFileToCalc(File.OpenRead(ofd.FileName), false); } } } @@ -1928,25 +1963,15 @@ namespace BizHawk.Client.EmuHawk private void TI83PaletteMenuItem_Click(object sender, EventArgs e) { - if (new TI83PaletteConfig().ShowDialog() == DialogResult.OK) - { - GlobalWin.OSD.AddMessage("Palette settings saved"); - } - else - { - GlobalWin.OSD.AddMessage("Palette config aborted"); - } + GlobalWin.OSD.AddMessage(new TI83PaletteConfig().ShowDialog() == DialogResult.OK + ? "Palette settings saved" + : "Palette config aborted"); } #endregion #region Atari - private void AtariSubMenu_DropDownOpened(object sender, EventArgs e) - { - - } - private void AtariSettingsToolStripMenuItem_Click(object sender, EventArgs e) { GenericCoreConfig.DoDialog(this, "Atari 2600 Settings"); @@ -1966,42 +1991,12 @@ namespace BizHawk.Client.EmuHawk config.GB.GBPrefs.DoGBPrefsDialog(this); } - private void GBForceDMGMenuItem_Click(object sender, EventArgs e) + private void LoadGbInSgbMenuItem_Click(object sender, EventArgs e) { - var s = ((Gameboy)Emulator).GetSyncSettings(); - s.ForceDMG ^= true; - PutCoreSyncSettings(s); + SnesGbInSgbMenuItem_Click(sender, e); } - private void GBAInCGBModeMenuItem_Click(object sender, EventArgs e) - { - var s = ((Gameboy)Emulator).GetSyncSettings(); - s.GBACGB ^= true; - PutCoreSyncSettings(s); - } - - private void GBMulticartCompatibilityMenuItem_Click(object sender, EventArgs e) - { - var s = ((Gameboy)Emulator).GetSyncSettings(); - s.MulticartCompat ^= true; - PutCoreSyncSettings(s); - } - - private void GBPaletteConfigMenuItem_Click(object sender, EventArgs e) - { - var gb = Emulator as Gameboy; - if (gb.IsCGBMode()) - CGBColorChooserForm.DoCGBColorChooserFormDialog(this); - else - ColorChooserForm.DoColorChooserFormDialog(this); - } - - private void LoadGBInSGBMenuItem_Click(object sender, EventArgs e) - { - SnesGBInSGBMenuItem_Click(sender, e); - } - - private void GBGPUViewerMenuItem_Click(object sender, EventArgs e) + private void GbGpuViewerMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); } @@ -2020,13 +2015,13 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Tools.Load(); } - private void GBAmGBAMenuItem_Click(object sender, EventArgs e) + private void UsemGBAMenuItem_Click(object sender, EventArgs e) { Global.Config.GBA_UsemGBA = true; FlagNeedsReboot(); } - private void GBAVBANextMenuItem_Click(object sender, EventArgs e) + private void UseVbaNextMenuItem_Click(object sender, EventArgs e) { Global.Config.GBA_UsemGBA = false; FlagNeedsReboot(); @@ -2038,7 +2033,7 @@ namespace BizHawk.Client.EmuHawk GBAVBANextMenuItem.Checked = Global.Config.GBA_UsemGBA == false; } - private void gBAWithMGBAToolStripMenuItem_Click(object sender, EventArgs e) + private void GbaWithmGBAMenuItem_Click(object sender, EventArgs e) { Global.Config.GBA_UsemGBA ^= true; FlagNeedsReboot(); @@ -2048,11 +2043,6 @@ namespace BizHawk.Client.EmuHawk #region PSX - private void PSXHashDiscsToolStripMenuItem_Click(object sender, EventArgs e) - { - new PSXHashDiscs().ShowDialog(); - } - private void PSXSubMenu_DropDownOpened(object sender, EventArgs e) { PSXControllerSettingsMenuItem.Enabled = !Global.MovieSession.Movie.IsActive; @@ -2063,13 +2053,32 @@ namespace BizHawk.Client.EmuHawk new PSXControllerConfigNew().ShowDialog(); } + private void PSXOptionsMenuItem_Click(object sender, EventArgs e) + { + var result = PSXOptions.DoSettingsDialog(this); + if (result == DialogResult.OK) + { + FrameBufferResized(); + } + } + + private void PSXDiscControlsMenuItem_Click(object sender, EventArgs e) + { + GlobalWin.Tools.Load().ScrollToPadSchema("Console"); + } + + private void PSXHashDiscsToolStripMenuItem_Click(object sender, EventArgs e) + { + new PSXHashDiscs().ShowDialog(); + } + #endregion #region SNES private void SNESSubMenu_DropDownOpened(object sender, EventArgs e) { - if ((Emulator as LibsnesCore).IsSGB) + if (((LibsnesCore)Emulator).IsSGB) { SnesGBInSGBMenuItem.Visible = true; SnesGBInSGBMenuItem.Checked = Global.Config.GB_AsSGB; @@ -2078,6 +2087,8 @@ namespace BizHawk.Client.EmuHawk { SnesGBInSGBMenuItem.Visible = false; } + + SNESControllerConfigurationMenuItem.Enabled = !Global.MovieSession.Movie.IsActive; } private void SNESDisplayMenuItem_DropDownOpened(object sender, EventArgs e) @@ -2127,12 +2138,12 @@ namespace BizHawk.Client.EmuHawk private void SnesObj1MenuItem_Click(object sender, EventArgs e) { - this.SNES_ToggleObj1(); + SNES_ToggleObj1(); } private void SnesObj2MenuItem_Click(object sender, EventArgs e) { - this.SNES_ToggleObj2(); + SNES_ToggleObj2(); } private void SnesObj3MenuItem_Click(object sender, EventArgs e) @@ -2145,12 +2156,17 @@ namespace BizHawk.Client.EmuHawk SNES_ToggleOBJ4(); } + private void SNESControllerConfigurationMenuItem_Click(object sender, EventArgs e) + { + new SNESControllerSettings().ShowDialog(); + } + private void SnesGfxDebuggerMenuItem_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); } - private void SnesGBInSGBMenuItem_Click(object sender, EventArgs e) + private void SnesGbInSgbMenuItem_Click(object sender, EventArgs e) { Global.Config.GB_AsSGB ^= true; FlagNeedsReboot(); @@ -2166,30 +2182,6 @@ namespace BizHawk.Client.EmuHawk SNESOptions.DoSettingsDialog(this); } - private void PSXOptionsMenuItem_Click(object sender, EventArgs e) - { - var result = PSXOptions.DoSettingsDialog(this); - if (result == DialogResult.OK) - { - FrameBufferResized(); - } - } - - private void PSXDiscControlsMenuItem_Click(object sender, EventArgs e) - { - GlobalWin.Tools.Load().ScrollToPadSchema("Console"); - } - - private void FlushSaveRAMMenuItem_Click(object sender, EventArgs e) - { - FlushSaveRAM(); - } - - private void FlushSaveRAMSubMenu_DropDownOpened(object sender, EventArgs e) - { - this.FlushSaveRAMMenuItem.ShortcutKeyDisplayString = Global.Config.HotkeyBindings["Flush SRAM"].Bindings; - } - #endregion #region Coleco @@ -2198,6 +2190,7 @@ namespace BizHawk.Client.EmuHawk { var ss = ((ColecoVision)Emulator).GetSyncSettings(); ColecoSkipBiosMenuItem.Checked = ss.SkipBiosIntro; + ColecoControllerSettingsMenuItem.Enabled = !Global.MovieSession.Movie.IsActive; } private void ColecoSkipBiosMenuItem_Click(object sender, EventArgs e) @@ -2228,11 +2221,8 @@ namespace BizHawk.Client.EmuHawk var s = ((N64)Emulator).GetSettings(); MupenStyleLagMenuItem.Checked = s.UseMupenStyleLag; - //var ss = (N64SyncSettings)Emulator.GetSyncSettings(); - //N64ExpansionSlotMenuItem.Checked = !ss.DisableExpansionSlot; - - N64ExpansionSlotMenuItem.Checked = (Emulator as N64).UsingExpansionSlot; - N64ExpansionSlotMenuItem.Enabled = !(Emulator as N64).IsOverridingUserExpansionSlotSetting; + N64ExpansionSlotMenuItem.Checked = ((N64)Emulator).UsingExpansionSlot; + N64ExpansionSlotMenuItem.Enabled = !((N64)Emulator).IsOverridingUserExpansionSlotSetting; } private void N64PluginSettingsMenuItem_Click(object sender, EventArgs e) @@ -2296,19 +2286,13 @@ namespace BizHawk.Client.EmuHawk private void SaturnPreferencesMenuItem_Click(object sender, EventArgs e) { GenericCoreConfig.DoDialog(this, "Saturn Settings"); - /* -- delete me, out of date - using (var dlg = new SaturnPrefs()) - { - dlg.ShowDialog(this); - } - * */ } #endregion #region DGB - private void DGBsettingsToolStripMenuItem_Click(object sender, EventArgs e) + private void DgbSettingsMenuItem_Click(object sender, EventArgs e) { config.GB.DGBPrefs.DoDGBPrefsDialog(this); } @@ -2327,7 +2311,7 @@ namespace BizHawk.Client.EmuHawk GenericCoreConfig.DoDialog(this, "Genesis Settings"); } - private void GenesisGameGenieECDC_Click(object sender, EventArgs e) + private void GenesisGameGenieEcDc_Click(object sender, EventArgs e) { GlobalWin.Tools.Load(); } @@ -2345,7 +2329,7 @@ namespace BizHawk.Client.EmuHawk #region Apple II - private void settingsToolStripMenuItem1_Click_1(object sender, EventArgs e) + private void AppleIISettingsMenuItem_Click(object sender, EventArgs e) { GenericCoreConfig.DoDialog(this, "Apple II Settings"); } @@ -2354,7 +2338,7 @@ namespace BizHawk.Client.EmuHawk { if (Emulator is AppleII) { - AppleDisksSubMenu.Enabled = (Emulator as AppleII).DiskCount > 1; + AppleDisksSubMenu.Enabled = ((AppleII)Emulator).DiskCount > 1; } } @@ -2364,7 +2348,7 @@ namespace BizHawk.Client.EmuHawk if (Emulator is AppleII) { - var appleII = Emulator as AppleII; + var appleII = (AppleII)Emulator; for (int i = 0; i < appleII.DiskCount; i++) { var menuItem = new ToolStripMenuItem @@ -2393,7 +2377,7 @@ namespace BizHawk.Client.EmuHawk { if (Emulator is C64) { - C64DisksSubMenu.Enabled = (Emulator as C64).DiskCount > 1; + C64DisksSubMenu.Enabled = ((C64)Emulator).DiskCount > 1; } } @@ -2403,7 +2387,7 @@ namespace BizHawk.Client.EmuHawk if (Emulator is C64) { - var c64 = Emulator as C64; + var c64 = (C64)Emulator; for (int i = 0; i < c64.DiskCount; i++) { var menuItem = new ToolStripMenuItem @@ -2433,6 +2417,11 @@ namespace BizHawk.Client.EmuHawk #region Intv + private void IntvSubMenu_DropDownOpened(object sender, EventArgs e) + { + IntVControllerSettingsMenuItem.Enabled = !Global.MovieSession.Movie.IsActive; + } + private void IntVControllerSettingsMenuItem_Click(object sender, EventArgs e) { new IntvControllerSettings().ShowDialog(); @@ -2442,6 +2431,11 @@ namespace BizHawk.Client.EmuHawk #region Help + private void HelpSubMenu_DropDownOpened(object sender, EventArgs e) + { + FeaturesMenuItem.Visible = VersionInfo.DeveloperBuild; + } + private void OnlineHelpMenuItem_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("http://tasvideos.org/BizHawk.html"); @@ -2452,6 +2446,11 @@ namespace BizHawk.Client.EmuHawk System.Diagnostics.Process.Start("http://tasvideos.org/forum/viewforum.php?f=64"); } + private void FeaturesMenuItem_Click(object sender, EventArgs e) + { + GlobalWin.Tools.Load(); + } + private void AboutMenuItem_Click(object sender, EventArgs e) { if (VersionInfo.DeveloperBuild) @@ -2477,8 +2476,16 @@ namespace BizHawk.Client.EmuHawk OpenRomContextMenuItem.Visible = Emulator.IsNull() || _inFullscreen; bool showMenuVisible = _inFullscreen; - if (!MainMenuStrip.Visible) showMenuVisible = true; //need to always be able to restore this as an emergency measure - if (_chromeless) showMenuVisible = true; //I decided this was always possible in chromeless mode, we'll see what they think + if (!MainMenuStrip.Visible) + { + showMenuVisible = true; // need to always be able to restore this as an emergency measure + } + + if (_chromeless) + { + showMenuVisible = true; // I decided this was always possible in chromeless mode, we'll see what they think + } + ShowMenuContextMenuItem.Visible = ShowMenuContextMenuSeparator.Visible = showMenuVisible; @@ -2540,8 +2547,7 @@ namespace BizHawk.Client.EmuHawk PathManager.SaveStatePrefix(Global.Game) + ".QuickSave" + Global.Config.SaveSlot + - ".State.bak" - ); + ".State.bak"); if (file.Exists) { @@ -2582,9 +2588,15 @@ namespace BizHawk.Client.EmuHawk SavestateTextContextMenuItem.Checked = false; switch (Global.Config.SaveStateType) { - case Config.SaveStateTypeE.Binary: SavestateBinaryContextMenuItem.Checked = true; break; - case Config.SaveStateTypeE.Text: SavestateTextContextMenuItem.Checked = true; break; - case Config.SaveStateTypeE.Default: SavestateTypeDefaultContextMenuItem.Checked = true; break; + case Config.SaveStateTypeE.Binary: + SavestateBinaryContextMenuItem.Checked = true; + break; + case Config.SaveStateTypeE.Text: + SavestateTextContextMenuItem.Checked = true; + break; + case Config.SaveStateTypeE.Default: + SavestateTypeDefaultContextMenuItem.Checked = true; + break; } } @@ -2637,18 +2649,18 @@ namespace BizHawk.Client.EmuHawk private void AddSubtitleContextMenuItem_Click(object sender, EventArgs e) { - //TODO: rethink this? + // TODO: rethink this? var subForm = new SubtitleMaker(); subForm.DisableFrame(); int index = -1; var sub = new Subtitle(); - for (int x = 0; x < Global.MovieSession.Movie.Subtitles.Count; x++) + for (int i = 0; i < Global.MovieSession.Movie.Subtitles.Count; i++) { - sub = Global.MovieSession.Movie.Subtitles[x]; + sub = Global.MovieSession.Movie.Subtitles[i]; if (Emulator.Frame == sub.Frame) { - index = x; + index = i; break; } } @@ -2687,13 +2699,12 @@ namespace BizHawk.Client.EmuHawk PathManager.SaveStatePrefix(Global.Game) + ".QuickSave" + Global.Config.SaveSlot + - ".State" - ); + ".State"); GlobalWin.OSD.AddMessage("Save slot " + Global.Config.SaveSlot + " restored."); } - private void ClearSRAMContextMenuItem_Click(object sender, EventArgs e) + private void ClearSramContextMenuItem_Click(object sender, EventArgs e) { CloseRom(clearSram: true); } @@ -2711,7 +2722,7 @@ namespace BizHawk.Client.EmuHawk private void DumpStatusButton_Click(object sender, EventArgs e) { string details = Emulator.CoreComm.RomStatusDetails; - if (!String.IsNullOrEmpty(details)) + if (!string.IsNullOrEmpty(details)) { GlobalWin.Sound.StopSound(); LogWindow.ShowReport("Dump Status Report", details, this); @@ -2761,6 +2772,7 @@ namespace BizHawk.Client.EmuHawk Global.Config.Input_Hotkey_OverrideOptions = 0; break; } + UpdateKeyPriorityIcon(); } @@ -2774,8 +2786,8 @@ namespace BizHawk.Client.EmuHawk private void ProfileFirstBootLabel_Click(object sender, EventArgs e) { - //We do not check if the user is actually setting a profile here. - //This is intentional. + // We do not check if the user is actually setting a profile here. + // This is intentional. var profileForm = new ProfileConfig(); profileForm.ShowDialog(); Global.Config.FirstBoot = false; @@ -2792,7 +2804,12 @@ namespace BizHawk.Client.EmuHawk if (result == DialogResult.Yes) { - System.Threading.ThreadPool.QueueUserWorkItem((s) => { using (System.Diagnostics.Process.Start(VersionInfo.HomePage)) { } }); + System.Threading.ThreadPool.QueueUserWorkItem(s => + { + using (System.Diagnostics.Process.Start(VersionInfo.HomePage)) + { + } + }); } else if (result == DialogResult.No) { @@ -2813,6 +2830,7 @@ namespace BizHawk.Client.EmuHawk { UnpauseEmulator(); } + _wasPaused = false; } } @@ -2825,14 +2843,17 @@ namespace BizHawk.Client.EmuHawk { _wasPaused = true; } + PauseEmulator(); } } - private void timerMouseIdle_Tick(object sender, EventArgs e) + private void TimerMouseIdle_Tick(object sender, EventArgs e) { if (_inFullscreen && Global.Config.DispChrome_Fullscreen_AutohideMouse) + { AutohideCursor(true); + } } private void MainForm_Enter(object sender, EventArgs e) @@ -2856,8 +2877,7 @@ namespace BizHawk.Client.EmuHawk if (Global.Config.ShowContextMenu && e.Button == MouseButtons.Right) { MainFormContextMenu.Show( - PointToScreen(new Point(e.X, e.Y + MainformMenu.Height)) - ); + PointToScreen(new Point(e.X, e.Y + MainformMenu.Height))); } } @@ -2909,7 +2929,7 @@ namespace BizHawk.Client.EmuHawk { try { - FormDragDrop_internal(sender, e); + FormDragDrop_Internal(sender, e); } catch (Exception ex) { @@ -2917,7 +2937,7 @@ namespace BizHawk.Client.EmuHawk } } - private void FormDragDrop_internal(object sender, DragEventArgs e) + private void FormDragDrop_Internal(object sender, DragEventArgs e) { _FormDragDrop_internal(sender, e); /* diff --git a/BizHawk.Client.EmuHawk/MainForm.Hotkey.cs b/BizHawk.Client.EmuHawk/MainForm.Hotkey.cs index 6300f9ca54..47495147cb 100644 --- a/BizHawk.Client.EmuHawk/MainForm.Hotkey.cs +++ b/BizHawk.Client.EmuHawk/MainForm.Hotkey.cs @@ -43,9 +43,11 @@ namespace BizHawk.Client.EmuHawk case "Screen Raw to Clipboard": // Ctrl+C clash. any tool that has such acc must check this. // maybe check if mainform has focus instead? - if (GlobalWin.Tools.IsLoaded()) - if (GlobalWin.Tools.Get().ContainsFocus) - break; + if (GlobalWin.Tools.IsLoaded() && GlobalWin.Tools.Get().ContainsFocus) + { + break; + } + TakeScreenshotToClipboard(); break; case "Screen Client to Clipboard": @@ -67,7 +69,7 @@ namespace BizHawk.Client.EmuHawk FlushSaveRAM(); break; case "Display FPS": - ToggleFPS(); + ToggleFps(); break; case "Frame Counter": ToggleFrameCounter(); @@ -77,6 +79,7 @@ namespace BizHawk.Client.EmuHawk { ToggleLagCounter(); } + break; case "Input Display": ToggleInputDisplay(); @@ -341,9 +344,11 @@ namespace BizHawk.Client.EmuHawk { type = " (on)"; } + Global.CheatList.ToList().ForEach(x => x.Toggle()); GlobalWin.OSD.AddMessage("Cheats toggled" + type); } + break; case "TAStudio": GlobalWin.Tools.Load(); @@ -358,45 +363,93 @@ namespace BizHawk.Client.EmuHawk // RAM Search case "Do Search": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.RamSearch.DoSearch(); - else return false; + } + else + { + return false; + } + break; case "New Search": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.RamSearch.NewSearch(); - else return false; + } + else + { + return false; + } + break; case "Previous Compare To": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.RamSearch.NextCompareTo(reverse: true); - else return false; + } + else + { + return false; + } + break; case "Next Compare To": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.RamSearch.NextCompareTo(); - else return false; + } + else + { + return false; + } + break; case "Previous Operator": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.RamSearch.NextOperator(reverse: true); - else return false; + } + else + { + return false; + } + break; case "Next Operator": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.RamSearch.NextOperator(); - else return false; + } + else + { + return false; + } + break; - //TAStudio + // TAStudio case "Add Branch": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.AddBranchExternal(); - else return false; + } + else + { + return false; + } + break; case "Delete Branch": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.RemoveBranchExtrenal(); - else return false; + } + else + { + return false; + } + break; case "Show Cursor": if (GlobalWin.Tools.IsLoaded()) @@ -404,72 +457,154 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Tools.TAStudio.SetVisibleIndex(); GlobalWin.Tools.TAStudio.RefreshDialog(); } - else return false; + else + { + return false; + } + break; case "Toggle Follow Cursor": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.TasPlaybackBox.FollowCursor ^= true; - else return false; + } + else + { + return false; + } + break; case "Toggle Auto-Restore": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.TasPlaybackBox.AutoRestore ^= true; - else return false; + } + else + { + return false; + } + break; case "Toggle Turbo Seek": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.TasPlaybackBox.TurboSeek ^= true; - else return false; + } + else + { + return false; + } + break; case "Clear Frames": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.ClearFramesExternal(); - else return false; + } + else + { + return false; + } + break; case "Insert Frame": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.InsertFrameExternal(); - else return false; + } + else + { + return false; + } + break; case "Delete Frames": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.DeleteFramesExternal(); - else return false; + } + else + { + return false; + } + break; case "Clone Frames": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.CloneFramesExternal(); - else return false; + } + else + { + return false; + } + break; case "Analog Increment": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.AnalogIncrementByOne(); - else return false; + } + else + { + return false; + } + break; case "Analog Decrement": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.AnalogDecrementByOne(); - else return false; + } + else + { + return false; + } + break; case "Analog Incr. by 10": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.AnalogIncrementByTen(); - else return false; + } + else + { + return false; + } + break; case "Analog Decr. by 10": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.AnalogDecrementByTen(); - else return false; + } + else + { + return false; + } + break; case "Analog Maximum": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.AnalogMax(); - else return false; + } + else + { + return false; + } + break; case "Analog Minimum": if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.AnalogMin(); - else return false; + } + else + { + return false; + } + break; // SNES @@ -506,10 +641,10 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Tools.VirtualPad.BumpAnalogValue(null, Global.Config.Analog_LargeChange); break; case "Y Down Small": - GlobalWin.Tools.VirtualPad.BumpAnalogValue(null, -(Global.Config.Analog_SmallChange)); + GlobalWin.Tools.VirtualPad.BumpAnalogValue(null, -Global.Config.Analog_SmallChange); break; case "Y Down Large": - GlobalWin.Tools.VirtualPad.BumpAnalogValue(null, -(Global.Config.Analog_LargeChange)); + GlobalWin.Tools.VirtualPad.BumpAnalogValue(null, -Global.Config.Analog_LargeChange); break; case "X Up Small": GlobalWin.Tools.VirtualPad.BumpAnalogValue(Global.Config.Analog_SmallChange, null); @@ -518,10 +653,10 @@ namespace BizHawk.Client.EmuHawk GlobalWin.Tools.VirtualPad.BumpAnalogValue(Global.Config.Analog_LargeChange, null); break; case "X Down Small": - GlobalWin.Tools.VirtualPad.BumpAnalogValue(-(Global.Config.Analog_SmallChange), null); + GlobalWin.Tools.VirtualPad.BumpAnalogValue(-Global.Config.Analog_SmallChange, null); break; case "X Down Large": - GlobalWin.Tools.VirtualPad.BumpAnalogValue(-(Global.Config.Analog_LargeChange), null); + GlobalWin.Tools.VirtualPad.BumpAnalogValue(-Global.Config.Analog_LargeChange, null); break; } diff --git a/BizHawk.Client.EmuHawk/MainForm.cs b/BizHawk.Client.EmuHawk/MainForm.cs index 6254823ef4..e36fbdb60a 100644 --- a/BizHawk.Client.EmuHawk/MainForm.cs +++ b/BizHawk.Client.EmuHawk/MainForm.cs @@ -18,17 +18,11 @@ using BizHawk.Bizware.BizwareGL; using BizHawk.Emulation.Common; using BizHawk.Emulation.Common.IEmulatorExtensions; -using BizHawk.Emulation.Cores.Atari.Atari2600; using BizHawk.Emulation.Cores.Calculators; using BizHawk.Emulation.Cores.Consoles.Nintendo.QuickNES; -using BizHawk.Emulation.Cores.Consoles.Sega.gpgx; -using BizHawk.Emulation.Cores.Nintendo.Gameboy; using BizHawk.Emulation.Cores.Nintendo.GBA; using BizHawk.Emulation.Cores.Nintendo.NES; using BizHawk.Emulation.Cores.Nintendo.SNES; -using BizHawk.Emulation.Cores.PCEngine; -using BizHawk.Emulation.Cores.Sega.MasterSystem; -using BizHawk.Emulation.DiscSystem; using BizHawk.Emulation.Cores.Nintendo.N64; using BizHawk.Client.EmuHawk.WinFormExtensions; @@ -36,6 +30,7 @@ using BizHawk.Client.EmuHawk.ToolExtensions; using BizHawk.Client.EmuHawk.CoreExtensions; using BizHawk.Client.ApiHawk; using BizHawk.Emulation.Common.Base_Implementations; +using BizHawk.Emulation.Cores.Nintendo.SNES9X; namespace BizHawk.Client.EmuHawk { @@ -55,12 +50,12 @@ namespace BizHawk.Client.EmuHawk ToolFormBase.UpdateCheatRelatedTools(null, null); RebootStatusBarIcon.Visible = false; UpdateNotification.Visible = false; - StatusBarDiskLightOnImage = Properties.Resources.LightOn; - StatusBarDiskLightOffImage = Properties.Resources.LightOff; - LinkCableOn = Properties.Resources.connect_16x16; - LinkCableOff = Properties.Resources.noconnect_16x16; + _statusBarDiskLightOnImage = Properties.Resources.LightOn; + _statusBarDiskLightOffImage = Properties.Resources.LightOff; + _linkCableOn = Properties.Resources.connect_16x16; + _linkCableOff = Properties.Resources.noconnect_16x16; UpdateCoreStatusBarButton(); - if (Global.Config.FirstBoot == true) + if (Global.Config.FirstBoot) { ProfileFirstBootLabel.Visible = true; } @@ -71,7 +66,11 @@ namespace BizHawk.Client.EmuHawk // New version notification UpdateChecker.CheckComplete += (s2, e2) => { - if (IsDisposed) return; + if (IsDisposed) + { + return; + } + this.BeginInvoke(() => { UpdateNotification.Visible = UpdateChecker.IsNewVersionAvailable; }); }; UpdateChecker.BeginCheck(); // Won't actually check unless enabled by user @@ -83,13 +82,15 @@ namespace BizHawk.Client.EmuHawk // its.. weird. dont ask. } - CoreComm CreateCoreComm() + private CoreComm CreateCoreComm() { - CoreComm ret = new CoreComm(ShowMessageCoreComm, NotifyCoreComm); - ret.ReleaseGLContext = (o) => GlobalWin.GLManager.ReleaseGLContext(o); - ret.RequestGLContext = (major,minor,forward) => GlobalWin.GLManager.CreateGLContext(major,minor,forward); - ret.ActivateGLContext = (gl) => GlobalWin.GLManager.Activate((GLManager.ContextRef)gl); - ret.DeactivateGLContext = () => GlobalWin.GLManager.Deactivate(); + CoreComm ret = new CoreComm(ShowMessageCoreComm, NotifyCoreComm) + { + ReleaseGLContext = o => GlobalWin.GLManager.ReleaseGLContext(o), + RequestGLContext = (major, minor, forward) => GlobalWin.GLManager.CreateGLContext(major, minor, forward), + ActivateGLContext = gl => GlobalWin.GLManager.Activate((GLManager.ContextRef)gl), + DeactivateGLContext = () => GlobalWin.GLManager.Deactivate() + }; return ret; } @@ -134,13 +135,17 @@ namespace BizHawk.Client.EmuHawk // we could background thread this later instead if we wanted to be real clever NES.BootGodDB.GetDatabaseBytes = () => { - string xmlPath = Path.Combine( PathManager.GetExeDirectoryAbsolute(), "gamedb", "NesCarts.xml" ); - string x7zPath = Path.Combine( PathManager.GetExeDirectoryAbsolute(), "gamedb", "NesCarts.7z" ); - bool loadXml = File.Exists( xmlPath ); - using (var NesCartFile = new HawkFile(loadXml ? xmlPath : x7zPath)) + string xmlPath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "NesCarts.xml"); + string x7zPath = Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "NesCarts.7z"); + bool loadXml = File.Exists(xmlPath); + using (var nesCartFile = new HawkFile(loadXml ? xmlPath : x7zPath)) { - if (!loadXml) { NesCartFile.BindFirst(); } - return NesCartFile + if (!loadXml) + { + nesCartFile.BindFirst(); + } + + return nesCartFile .GetStream() .ReadAllBytes(); } @@ -170,6 +175,7 @@ namespace BizHawk.Client.EmuHawk { cmdLoadSlot = arg.Substring(arg.IndexOf('=') + 1); } + if (arg.StartsWith("--load-state=")) { cmdLoadState = arg.Substring(arg.IndexOf('=') + 1); @@ -187,9 +193,12 @@ namespace BizHawk.Client.EmuHawk var list = arg.Substring(arg.IndexOf('=') + 1); var items = list.Split(','); _currAviWriterFrameList = new HashSet(); - for (int j = 0; j < items.Length; j++) - _currAviWriterFrameList.Add(int.Parse(items[j])); - //automatically set dump length to maximum frame + foreach (string item in items) + { + _currAviWriterFrameList.Add(int.Parse(item)); + } + + // automatically set dump length to maximum frame _autoDumpLength = _currAviWriterFrameList.OrderBy(x => x).Last(); } else if (arg.StartsWith("--dump-name=")) @@ -220,7 +229,7 @@ namespace BizHawk.Client.EmuHawk Database.LoadDatabase(Path.Combine(PathManager.GetExeDirectoryAbsolute(), "gamedb", "gamedb.txt")); - //TODO GL - a lot of disorganized wiring-up here + // TODO GL - a lot of disorganized wiring-up here CGC.CGCBinPath = Path.Combine(PathManager.GetDllDirectory(), "cgc.exe"); PresentationPanel = new PresentationPanel(); PresentationPanel.GraphicsControl.MainWindow = true; @@ -228,7 +237,7 @@ namespace BizHawk.Client.EmuHawk Controls.Add(PresentationPanel); Controls.SetChildIndex(PresentationPanel, 0); - //TODO GL - move these event handlers somewhere less obnoxious line in the On* overrides + // TODO GL - move these event handlers somewhere less obnoxious line in the On* overrides Load += (o, e) => { AllowDrop = true; @@ -240,11 +249,12 @@ namespace BizHawk.Client.EmuHawk { if (GlobalWin.Tools.AskSave()) { - //zero 03-nov-2015 - close game after other steps. tools might need to unhook themselves from a core. + // zero 03-nov-2015 - close game after other steps. tools might need to unhook themselves from a core. Global.MovieSession.Movie.Stop(); GlobalWin.Tools.Close(); CloseGame(); - //does this need to be last for any particular reason? do tool dialogs persist settings when closing? + + // does this need to be last for any particular reason? do tool dialogs persist settings when closing? SaveConfig(); } else @@ -290,19 +300,26 @@ namespace BizHawk.Client.EmuHawk CoreFileProvider.SyncCoreCommInputSignals(comm); Emulator = new NullEmulator(comm, Global.Config.GetCoreSettings()); Global.ActiveController = new Controller(NullController.Instance.Definition); - Global.AutoFireController = Global.AutofireNullControls; + Global.AutoFireController = _autofireNullControls; Global.AutofireStickyXORAdapter.SetOnOffPatternFromConfig(); - try { GlobalWin.Sound = new Sound(Handle); } + try + { + GlobalWin.Sound = new Sound(Handle); + } catch { string message = "Couldn't initialize sound device! Try changing the output method in Sound config."; if (Global.Config.SoundOutputMethod == Config.ESoundOutputMethod.DirectSound) + { message = "Couldn't initialize DirectSound! Things may go poorly for you. Try changing your sound driver to 44.1khz instead of 48khz in mmsys.cpl."; + } + MessageBox.Show(message, "Initialization Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Global.Config.SoundOutputMethod = Config.ESoundOutputMethod.Dummy; GlobalWin.Sound = new Sound(Handle); } + GlobalWin.Sound.StartSound(); InputManager.RewireInputChain(); GlobalWin.Tools = new ToolManager(this); @@ -327,7 +344,7 @@ namespace BizHawk.Client.EmuHawk if (cmdRom != null) { // Commandline should always override auto-load - LoadRom(cmdRom, new MainForm.LoadRomArgs() { OpenAdvanced = new OpenAdvanced_OpenRom() }); + LoadRom(cmdRom, new LoadRomArgs { OpenAdvanced = new OpenAdvanced_OpenRom() }); if (Global.Game == null) { MessageBox.Show("Failed to load " + cmdRom + " specified on commandline"); @@ -359,10 +376,10 @@ namespace BizHawk.Client.EmuHawk } // Copy pasta from drag & drop - string errorMsg; - string warningMsg; if (MovieImport.IsValidMovieExtension(Path.GetExtension(cmdMovie))) { + string errorMsg; + string warningMsg; var imported = MovieImport.ImportFile(cmdMovie, out errorMsg, out warningMsg); if (!string.IsNullOrEmpty(errorMsg)) { @@ -397,7 +414,6 @@ namespace BizHawk.Client.EmuHawk // If user picked a game, then do the autoload logic if (!Global.Game.IsNullInstance) { - if (File.Exists(Global.Config.RecentMovies.MostRecent)) { StartNewMovie(MovieService.Get(Global.Config.RecentMovies.MostRecent), false); @@ -461,27 +477,27 @@ namespace BizHawk.Client.EmuHawk PresentationPanel.Control.Paint += (o, e) => { - //I would like to trigger a repaint here, but this isnt done yet + // I would like to trigger a repaint here, but this isnt done yet }; } - private bool _supressSyncSettingsWarning = false; + private readonly bool _supressSyncSettingsWarning; public int ProgramRunLoop() { - CheckMessages(); //can someone leave a note about why this is needed? + CheckMessages(); // can someone leave a note about why this is needed? LogConsole.PositionConsole(); - //needs to be done late, after the log console snaps on top - //fullscreen should snap on top even harder! + // needs to be done late, after the log console snaps on top + // fullscreen should snap on top even harder! if (_needsFullscreenOnLoad) { _needsFullscreenOnLoad = false; ToggleFullscreen(); } - //incantation required to get the program reliably on top of the console window - //we might want it in ToggleFullscreen later, but here, it needs to happen regardless + // incantation required to get the program reliably on top of the console window + // we might want it in ToggleFullscreen later, but here, it needs to happen regardless BringToFront(); Activate(); BringToFront(); @@ -494,7 +510,7 @@ namespace BizHawk.Client.EmuHawk // handle events and dispatch as a hotkey action, or a hotkey button, or an input button ProcessInput(); - Global.ClientControls.LatchFromPhysical(HotkeyCoalescer); + Global.ClientControls.LatchFromPhysical(_hotkeyCoalescer); Global.ActiveController.LatchFromPhysical(Global.ControllerInputCoalescer); @@ -539,6 +555,7 @@ namespace BizHawk.Client.EmuHawk { break; } + if (Global.Config.DispSpeedupFeatures != 0) { Thread.Sleep(0); @@ -555,17 +572,16 @@ namespace BizHawk.Client.EmuHawk /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { - //NOTE: this gets called twice sometimes. once by using() in Program.cs and once from winforms internals when the form is closed... - + // NOTE: this gets called twice sometimes. once by using() in Program.cs and once from winforms internals when the form is closed... if (GlobalWin.DisplayManager != null) { GlobalWin.DisplayManager.Dispose(); GlobalWin.DisplayManager = null; } - if (disposing && (components != null)) + if (disposing) { - components.Dispose(); + components?.Dispose(); } base.Dispose(disposing); @@ -591,10 +607,7 @@ namespace BizHawk.Client.EmuHawk } _emulatorPaused = value; - if (OnPauseChanged != null) - { - OnPauseChanged(this, new PauseChangedEventArgs(_emulatorPaused)); - } + OnPauseChanged?.Invoke(this, new PauseChangedEventArgs(_emulatorPaused)); } } @@ -615,25 +628,27 @@ namespace BizHawk.Client.EmuHawk #region Properties - public string CurrentlyOpenRom; //todo - delete me and use only args instead - public LoadRomArgs CurrentlyOpenRomArgs; - public bool PauseAVI = false; - public bool PressFrameAdvance = false; - public bool HoldFrameAdvance = false; // necessary for tastudio > button - public bool PressRewind = false; // necessary for tastudio < button - public bool FastForward = false; - public bool TurboFastForward = false; - public bool RestoreReadWriteOnStop = false; + public string CurrentlyOpenRom { get; private set; } // todo - delete me and use only args instead + public LoadRomArgs CurrentlyOpenRomArgs { get; private set; } + public bool PauseAvi { get; set; } + public bool PressFrameAdvance { get; set; } + public bool HoldFrameAdvance { get; set; } // necessary for tastudio > button + public bool PressRewind { get; set; } // necessary for tastudio < button + public bool FastForward { get; set; } - //runloop won't exec lua - public bool SuppressLua; + // runloop won't exec lua + public bool SuppressLua { get; set; } - public long MouseWheelTracker; + public long MouseWheelTracker { get; private set; } private int? _pauseOnFrame; public int? PauseOnFrame // If set, upon completion of this frame, the client wil pause { - get { return _pauseOnFrame; } + get + { + return _pauseOnFrame; + } + set { _pauseOnFrame = value; @@ -648,26 +663,11 @@ namespace BizHawk.Client.EmuHawk } } - public bool IsSeeking - { - get { return PauseOnFrame.HasValue; } - } + public bool IsSeeking => PauseOnFrame.HasValue; - public bool IsTurboSeeking - { - get - { - return PauseOnFrame.HasValue && Global.Config.TurboSeek; - } - } + private bool IsTurboSeeking => PauseOnFrame.HasValue && Global.Config.TurboSeek; - public bool IsTurboing - { - get - { - return Global.ClientControls["Turbo"] || IsTurboSeeking; - } - } + private bool IsTurboing => Global.ClientControls["Turbo"] || IsTurboSeeking; #endregion @@ -693,7 +693,7 @@ namespace BizHawk.Client.EmuHawk /// /// Controls whether the app generates input events. should be turned off for most modal dialogs /// - public bool AllowInput(bool yield_alt) + public bool AllowInput(bool yieldAlt) { // the main form gets input if (ActiveForm == this) @@ -701,21 +701,27 @@ namespace BizHawk.Client.EmuHawk return true; } - //even more special logic for TAStudio: - //TODO - implement by event filter in TAStudio + // even more special logic for TAStudio: + // TODO - implement by event filter in TAStudio if (ActiveForm is TAStudio) { - if(yield_alt) return false; - var ts = ActiveForm as TAStudio; - if(ts.IsInMenuLoop) + if (yieldAlt) + { return false; + } + + var ts = (TAStudio)ActiveForm; + if (ts.IsInMenuLoop) + { + return false; + } } // modals that need to capture input for binding purposes get input, of course - if (ActiveForm is HotkeyConfig || - ActiveForm is ControllerConfig || - ActiveForm is TAStudio || - ActiveForm is VirtualpadTool) + if (ActiveForm is HotkeyConfig + || ActiveForm is ControllerConfig + || ActiveForm is TAStudio + || ActiveForm is VirtualpadTool) { return true; } @@ -731,9 +737,13 @@ namespace BizHawk.Client.EmuHawk // TODO: make this an actual property, set it when loading a Rom, and pass it dialogs, etc // This is a quick hack to reduce the dependency on Global.Emulator - public IEmulator Emulator + private IEmulator Emulator { - get { return Global.Emulator; } + get + { + return Global.Emulator; + } + set { Global.Emulator = value; @@ -758,16 +768,18 @@ namespace BizHawk.Client.EmuHawk base.OnDeactivate(e); } - public void ProcessInput() + private void ProcessInput() { - ControllerInputCoalescer conInput = Global.ControllerInputCoalescer as ControllerInputCoalescer; + ControllerInputCoalescer conInput = (ControllerInputCoalescer)Global.ControllerInputCoalescer; for (;;) { - // loop through all available events var ie = Input.Instance.DequeueEvent(); - if (ie == null) { break; } + if (ie == null) + { + break; + } // useful debugging: // Console.WriteLine(ie); @@ -789,6 +801,7 @@ namespace BizHawk.Client.EmuHawk SendAltKeyChar(c); } } + if (ie.LogicalButton.Alt && ie.LogicalButton.Button == "Space") { SendPlainAltKey(32); @@ -818,7 +831,7 @@ namespace BizHawk.Client.EmuHawk // hotkeys which arent handled as actions get coalesced as pollable virtual client buttons if (!handled) { - HotkeyCoalescer.Receive(ie); + _hotkeyCoalescer.Receive(ie); } break; @@ -835,9 +848,10 @@ namespace BizHawk.Client.EmuHawk // hotkeys which arent handled as actions get coalesced as pollable virtual client buttons if (!handled) { - HotkeyCoalescer.Receive(ie); + _hotkeyCoalescer.Receive(ie); } } + break; case 2: // Hotkeys override Input handled = false; @@ -849,10 +863,10 @@ namespace BizHawk.Client.EmuHawk // hotkeys which arent handled as actions get coalesced as pollable virtual client buttons if (!handled) { - HotkeyCoalescer.Receive(ie); + _hotkeyCoalescer.Receive(ie); // Check for hotkeys that may not be handled through Checkhotkey() method, reject controller input mapped to these - if (!triggers.Any(trigger => IsInternalHotkey(trigger))) + if (!triggers.Any(IsInternalHotkey)) { conInput.Receive(ie); } @@ -860,7 +874,6 @@ namespace BizHawk.Client.EmuHawk break; } - } // foreach event // also handle floats @@ -869,16 +882,16 @@ namespace BizHawk.Client.EmuHawk // hackish if (o.Item1 == "WMouse X") { - var P = GlobalWin.DisplayManager.UntransformPoint(new Point((int)o.Item2, 0)); - float x = P.X / (float)_currentVideoProvider.BufferWidth; - return new Tuple("WMouse X", x * 20000 - 10000); + var p = GlobalWin.DisplayManager.UntransformPoint(new Point((int)o.Item2, 0)); + float x = p.X / (float)_currentVideoProvider.BufferWidth; + return new Tuple("WMouse X", (x * 20000) - 10000); } if (o.Item1 == "WMouse Y") { - var P = GlobalWin.DisplayManager.UntransformPoint(new Point(0, (int)o.Item2)); - float y = P.Y / (float)_currentVideoProvider.BufferHeight; - return new Tuple("WMouse Y", y * 20000 - 10000); + var p = GlobalWin.DisplayManager.UntransformPoint(new Point(0, (int)o.Item2)); + float y = p.Y / (float)_currentVideoProvider.BufferHeight; + return new Tuple("WMouse Y", (y * 20000) - 10000); } return o; @@ -887,11 +900,15 @@ namespace BizHawk.Client.EmuHawk public void RebootCore() { - var ioa = OpenAdvancedSerializer.ParseWithLegacy(CurrentlyOpenRomPoopForAdvancedLoaderPleaseRefactorME); + var ioa = OpenAdvancedSerializer.ParseWithLegacy(_currentlyOpenRomPoopForAdvancedLoaderPleaseRefactorMe); if (ioa is OpenAdvanced_LibretroNoGame) + { LoadRom("", CurrentlyOpenRomArgs); + } else + { LoadRom(ioa.SimplePath, CurrentlyOpenRomArgs); + } } public void PauseEmulator() @@ -935,18 +952,22 @@ namespace BizHawk.Client.EmuHawk using (var bb = Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage()) { using (var img = bb.ToSysdrawingBitmap()) + { Clipboard.SetImage(img); + } } GlobalWin.OSD.AddMessage("Screenshot (raw) saved to clipboard."); } - public void TakeScreenshotClientToClipboard() + private void TakeScreenshotClientToClipboard() { using (var bb = GlobalWin.DisplayManager.RenderOffscreen(_currentVideoProvider, Global.Config.Screenshot_CaptureOSD)) { using (var img = bb.ToSysdrawingBitmap()) + { Clipboard.SetImage(img); + } } GlobalWin.OSD.AddMessage("Screenshot (client) saved to clipboard."); @@ -958,20 +979,28 @@ namespace BizHawk.Client.EmuHawk string prefix = PathManager.ScreenshotPrefix(Global.Game); var ts = DateTime.Now; - string fname_bare = string.Format(fmt, prefix, ts, ""); + string fnameBare = string.Format(fmt, prefix, ts, ""); string fname = string.Format(fmt, prefix, ts, " (0)"); - //if the (0) filename exists, do nothing. we'll bump up the number later - //if the bare filename exists, move it to (0) - //otherwise, no related filename exists, and we can proceed with the bare filename - if (File.Exists(fname)) { } - else if (File.Exists(fname_bare)) - File.Move(fname_bare, fname); - else fname = fname_bare; + // if the (0) filename exists, do nothing. we'll bump up the number later + // if the bare filename exists, move it to (0) + // otherwise, no related filename exists, and we can proceed with the bare filename + if (File.Exists(fname)) + { + } + else if (File.Exists(fnameBare)) + { + File.Move(fnameBare, fname); + } + else + { + fname = fnameBare; + } + int seq = 0; while (File.Exists(fname)) { - var sequence = string.Format(" ({0})", seq++); + var sequence = $" ({seq++})"; fname = string.Format(fmt, prefix, ts, sequence); } @@ -989,15 +1018,17 @@ namespace BizHawk.Client.EmuHawk using (var bb = Global.Config.Screenshot_CaptureOSD ? CaptureOSD() : MakeScreenshotImage()) { using (var img = bb.ToSysdrawingBitmap()) + { img.Save(fi.FullName, ImageFormat.Png); + } } + /* using (var fs = new FileStream(path + "_test.bmp", FileMode.OpenOrCreate, FileAccess.Write)) QuickBmpFile.Save(Emulator.VideoProvider(), fs, r.Next(50, 500), r.Next(50, 500)); */ GlobalWin.OSD.AddMessage(fi.Name + " saved."); } - //static Random r = new Random(); public void FrameBufferResized() { @@ -1015,16 +1046,17 @@ namespace BizHawk.Client.EmuHawk for (; zoom >= 1; zoom--) { lastComputedSize = GlobalWin.DisplayManager.CalculateClientSize(_currentVideoProvider, zoom); - if ((((lastComputedSize.Width) + borderWidth) < area.Width) - && (((lastComputedSize.Height) + borderHeight) < area.Height)) + if (lastComputedSize.Width + borderWidth < area.Width + && lastComputedSize.Height + borderHeight < area.Height) { break; } } - Console.WriteLine("Selecting display size " + lastComputedSize.ToString()); + + Console.WriteLine("Selecting display size " + lastComputedSize); // Change size - Size = new Size((lastComputedSize.Width) + borderWidth, ((lastComputedSize.Height) + borderHeight)); + Size = new Size(lastComputedSize.Width + borderWidth, lastComputedSize.Height + borderHeight); PerformLayout(); PresentationPanel.Resized = true; @@ -1044,16 +1076,11 @@ namespace BizHawk.Client.EmuHawk } } - public bool IsInFullscreen - { - get { return _inFullscreen; } - } - - public void SynchChrome() + private void SynchChrome() { if (_inFullscreen) { - //TODO - maybe apply a hack tracked during fullscreen here to override it + // TODO - maybe apply a hack tracked during fullscreen here to override it FormBorderStyle = FormBorderStyle.None; MainMenuStrip.Visible = Global.Config.DispChrome_MenuFullscreen && !_chromeless; MainStatusBar.Visible = Global.Config.DispChrome_StatusBarFullscreen && !_chromeless; @@ -1064,11 +1091,17 @@ namespace BizHawk.Client.EmuHawk MainMenuStrip.Visible = Global.Config.DispChrome_MenuWindowed && !_chromeless; MaximizeBox = MinimizeBox = Global.Config.DispChrome_CaptionWindowed && !_chromeless; if (Global.Config.DispChrome_FrameWindowed == 0 || _chromeless) - FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; + { + FormBorderStyle = FormBorderStyle.None; + } else if (Global.Config.DispChrome_FrameWindowed == 1) - FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; + { + FormBorderStyle = FormBorderStyle.SizableToolWindow; + } else if (Global.Config.DispChrome_FrameWindowed == 2) - FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable; + { + FormBorderStyle = FormBorderStyle.Sizable; + } } } @@ -1076,24 +1109,26 @@ namespace BizHawk.Client.EmuHawk { AutohideCursor(false); - //prohibit this operation if the current controls include LMouse + // prohibit this operation if the current controls include LMouse if (allowSuppress) { if (Global.ActiveController.HasBinding("WMouse L")) + { return; + } } if (!_inFullscreen) { SuspendLayout(); #if WINDOWS - //Work around an AMD driver bug in >= vista: - //It seems windows will activate opengl fullscreen mode when a GL control is occupying the exact space of a screen (0,0 and dimensions=screensize) - //AMD cards manifest a problem under these circumstances, flickering other monitors. - //It isnt clear whether nvidia cards are failing to employ this optimization, or just not flickering. - //(this could be determined with more work; other side affects of the fullscreen mode include: corrupted taskbar, no modal boxes on top of GL control, no screenshots) - //At any rate, we can solve this by adding a 1px black border around the GL control - //Please note: It is important to do this before resizing things, otherwise momentarily a GL control without WS_BORDER will be at the magic dimensions and cause the flakeout + // Work around an AMD driver bug in >= vista: + // It seems windows will activate opengl fullscreen mode when a GL control is occupying the exact space of a screen (0,0 and dimensions=screensize) + // AMD cards manifest a problem under these circumstances, flickering other monitors. + // It isnt clear whether nvidia cards are failing to employ this optimization, or just not flickering. + // (this could be determined with more work; other side affects of the fullscreen mode include: corrupted taskbar, no modal boxes on top of GL control, no screenshots) + // At any rate, we can solve this by adding a 1px black border around the GL control + // Please note: It is important to do this before resizing things, otherwise momentarily a GL control without WS_BORDER will be at the magic dimensions and cause the flakeout if (Global.Config.DispFullscreenHacks && Global.Config.DispMethod == Config.EDispMethod.OpenGL) { //ATTENTION: this causes the statusbar to not work well, since the backcolor is now set to black instead of SystemColors.Control. @@ -1102,8 +1137,8 @@ namespace BizHawk.Client.EmuHawk Padding = new Padding(1); BackColor = Color.Black; - //FUTURE WORK: - //re-add this padding back into the display manager (so the image will get cut off a little but, but a few more resolutions will fully fit into the screen) + // FUTURE WORK: + // re-add this padding back into the display manager (so the image will get cut off a little but, but a few more resolutions will fully fit into the screen) } #endif @@ -1111,7 +1146,7 @@ namespace BizHawk.Client.EmuHawk _inFullscreen = true; SynchChrome(); - WindowState = FormWindowState.Maximized; //be sure to do this after setting the chrome, otherwise it wont work fully + WindowState = FormWindowState.Maximized; // be sure to do this after setting the chrome, otherwise it wont work fully ResumeLayout(); PresentationPanel.Resized = true; @@ -1123,10 +1158,10 @@ namespace BizHawk.Client.EmuHawk WindowState = FormWindowState.Normal; #if WINDOWS - //do this even if DispFullscreenHacks arent enabled, to restore it in case it changed underneath us or something + // do this even if DispFullscreenHacks arent enabled, to restore it in case it changed underneath us or something Padding = new Padding(0); - //it's important that we set the form color back to this, because the statusbar icons blend onto the mainform, not onto the statusbar-- - //so we need the statusbar and mainform backdrop color to match + // it's important that we set the form color back to this, because the statusbar icons blend onto the mainform, not onto the statusbar-- + // so we need the statusbar and mainform backdrop color to match BackColor = SystemColors.Control; #endif @@ -1140,7 +1175,7 @@ namespace BizHawk.Client.EmuHawk } } - public void OpenLuaConsole() + private void OpenLuaConsole() { #if WINDOWS GlobalWin.Tools.Load(); @@ -1176,14 +1211,26 @@ namespace BizHawk.Client.EmuHawk _unthrottled = false; } - void ThrottleMessage() + private void ThrottleMessage() { string ttype = ":(none)"; - if (Global.Config.SoundThrottle) { ttype = ":Sound"; } - if (Global.Config.VSyncThrottle) { ttype = string.Format(":Vsync{0}", Global.Config.VSync ? "[ena]" : "[dis]"); } - if (Global.Config.ClockThrottle) { ttype = ":Clock"; } + if (Global.Config.SoundThrottle) + { + ttype = ":Sound"; + } + + if (Global.Config.VSyncThrottle) + { + ttype = $":Vsync{(Global.Config.VSync ? "[ena]" : "[dis]")}"; + } + + if (Global.Config.ClockThrottle) + { + ttype = ":Clock"; + } + string xtype = _unthrottled ? "Unthrottled" : "Throttled"; - string msg = string.Format("{0}{1} ", xtype, ttype); + string msg = $"{xtype}{ttype} "; GlobalWin.OSD.AddMessage(msg); } @@ -1209,13 +1256,16 @@ namespace BizHawk.Client.EmuHawk } } - private LibsnesCore AsSNES { get { return Emulator as LibsnesCore; } } + private LibsnesCore AsSNES => Emulator as LibsnesCore; // TODO: Clean Me! - - public void SNES_ToggleBG1(bool? setto = null) + private void SNES_ToggleBG1(bool? setto = null) { - if (!(Emulator is LibsnesCore)) return; + if (!(Emulator is LibsnesCore)) + { + return; + } + var s = AsSNES.GetSettings(); if (setto.HasValue) { @@ -1230,9 +1280,13 @@ namespace BizHawk.Client.EmuHawk GlobalWin.OSD.AddMessage(s.ShowBG1_1 ? "BG 1 Layer On" : "BG 1 Layer Off"); } - public void SNES_ToggleBG2(bool? setto = null) + private void SNES_ToggleBG2(bool? setto = null) { - if (!(Emulator is LibsnesCore)) return; + if (!(Emulator is LibsnesCore)) + { + return; + } + var s = AsSNES.GetSettings(); if (setto.HasValue) { @@ -1247,9 +1301,13 @@ namespace BizHawk.Client.EmuHawk GlobalWin.OSD.AddMessage(s.ShowBG2_1 ? "BG 2 Layer On" : "BG 2 Layer Off"); } - public void SNES_ToggleBG3(bool? setto = null) + private void SNES_ToggleBG3(bool? setto = null) { - if (!(Emulator is LibsnesCore)) return; + if (!(Emulator is LibsnesCore)) + { + return; + } + var s = AsSNES.GetSettings(); if (setto.HasValue) { @@ -1264,9 +1322,13 @@ namespace BizHawk.Client.EmuHawk GlobalWin.OSD.AddMessage(s.ShowBG3_1 ? "BG 3 Layer On" : "BG 3 Layer Off"); } - public void SNES_ToggleBG4(bool? setto = null) + private void SNES_ToggleBG4(bool? setto = null) { - if (!(Emulator is LibsnesCore)) return; + if (!(Emulator is LibsnesCore)) + { + return; + } + var s = AsSNES.GetSettings(); if (setto.HasValue) { @@ -1281,9 +1343,13 @@ namespace BizHawk.Client.EmuHawk GlobalWin.OSD.AddMessage(s.ShowBG4_1 ? "BG 4 Layer On" : "BG 4 Layer Off"); } - public void SNES_ToggleObj1(bool? setto = null) + private void SNES_ToggleObj1(bool? setto = null) { - if (!(Emulator is LibsnesCore)) return; + if (!(Emulator is LibsnesCore)) + { + return; + } + var s = AsSNES.GetSettings(); if (setto.HasValue) { @@ -1298,9 +1364,13 @@ namespace BizHawk.Client.EmuHawk GlobalWin.OSD.AddMessage(s.ShowOBJ_0 ? "OBJ 1 Layer On" : "OBJ 1 Layer Off"); } - public void SNES_ToggleObj2(bool? setto = null) + private void SNES_ToggleObj2(bool? setto = null) { - if (!(Emulator is LibsnesCore)) return; + if (!(Emulator is LibsnesCore)) + { + return; + } + var s = AsSNES.GetSettings(); if (setto.HasValue) { @@ -1310,13 +1380,18 @@ namespace BizHawk.Client.EmuHawk { s.ShowOBJ_1 ^= true; } + AsSNES.PutSettings(s); GlobalWin.OSD.AddMessage(s.ShowOBJ_1 ? "OBJ 2 Layer On" : "OBJ 2 Layer Off"); } - public void SNES_ToggleOBJ3(bool? setto = null) + private void SNES_ToggleOBJ3(bool? setto = null) { - if (!(Emulator is LibsnesCore)) return; + if (!(Emulator is LibsnesCore)) + { + return; + } + var s = AsSNES.GetSettings(); if (setto.HasValue) { @@ -1331,9 +1406,13 @@ namespace BizHawk.Client.EmuHawk GlobalWin.OSD.AddMessage(s.ShowOBJ_2 ? "OBJ 3 Layer On" : "OBJ 3 Layer Off"); } - public void SNES_ToggleOBJ4(bool? setto = null) + private void SNES_ToggleOBJ4(bool? setto = null) { - if (!(Emulator is LibsnesCore)) return; + if (!(Emulator is LibsnesCore)) + { + return; + } + var s = AsSNES.GetSettings(); if (setto.HasValue) { @@ -1348,6 +1427,37 @@ namespace BizHawk.Client.EmuHawk GlobalWin.OSD.AddMessage(s.ShowOBJ_3 ? "OBJ 4 Layer On" : "OBJ 4 Layer Off"); } + public bool RunLibretroCoreChooser() + { + var ofd = new OpenFileDialog(); + + if (Global.Config.LibretroCore != null) + { + ofd.FileName = Path.GetFileName(Global.Config.LibretroCore); + ofd.InitialDirectory = Path.GetDirectoryName(Global.Config.LibretroCore); + } + else + { + ofd.InitialDirectory = PathManager.GetPathType("Libretro", "Cores"); + if (!Directory.Exists(ofd.InitialDirectory)) + { + Directory.CreateDirectory(ofd.InitialDirectory); + } + } + + ofd.RestoreDirectory = true; + ofd.Filter = "Libretro Cores (*.dll)|*.dll"; + + if (ofd.ShowDialog() == DialogResult.Cancel) + { + return false; + } + + Global.Config.LibretroCore = ofd.FileName; + + return true; + } + #endregion #region Private variables @@ -1357,7 +1467,9 @@ namespace BizHawk.Client.EmuHawk // AVI/WAV state private IVideoWriter _currAviWriter; - private HashSet _currAviWriterFrameList; + private readonly HashSet _currAviWriterFrameList; + + private AutofireController _autofireNullControls; // Sound refator TODO: we can enforce async mode here with a property that gets/sets this but does an async check private ISoundProvider _aviSoundInputAsync; // Note: This sound provider must be in async mode! @@ -1402,24 +1514,36 @@ namespace BizHawk.Client.EmuHawk private readonly bool _autoCloseOnDump; private int _lastOpenRomFilter; - //chrome is never shown, even in windowed mode + // chrome is never shown, even in windowed mode private readonly bool _chromeless; // Resources - Bitmap StatusBarDiskLightOnImage, StatusBarDiskLightOffImage; - Bitmap LinkCableOn, LinkCableOff; + private Bitmap _statusBarDiskLightOnImage; + private Bitmap _statusBarDiskLightOffImage; + private Bitmap _linkCableOn; + private Bitmap _linkCableOff; // input state which has been destined for game controller inputs are coalesced here // public static ControllerInputCoalescer ControllerInputCoalescer = new ControllerInputCoalescer(); // input state which has been destined for client hotkey consumption are colesced here - private readonly InputCoalescer HotkeyCoalescer = new InputCoalescer(); + private readonly InputCoalescer _hotkeyCoalescer = new InputCoalescer(); - public PresentationPanel PresentationPanel { get; set; } + public PresentationPanel PresentationPanel { get; } #endregion #region Private methods + private void SetStatusBar() + { + if (!_inFullscreen) + { + MainStatusBar.Visible = Global.Config.DispChrome_StatusBarWindowed; + PerformLayout(); + FrameBufferResized(); + } + } + private void SetWindowText() { string str = ""; @@ -1427,11 +1551,11 @@ namespace BizHawk.Client.EmuHawk if (_inResizeLoop) { var size = PresentationPanel.NativeSize; - float AR = (float)size.Width / size.Height; - str += $"({size.Width}x{size.Height})={AR} - "; + float ar = (float)size.Width / size.Height; + str += $"({size.Width}x{size.Height})={ar} - "; } - //we need to display FPS somewhere, in this case + // we need to display FPS somewhere, in this case if (Global.Config.DispSpeedupFeatures == 0) { str += $"({_lastFps:0} fps) - "; @@ -1562,7 +1686,7 @@ namespace BizHawk.Client.EmuHawk // GBA meteor core might not know how big the saveram ought to be, so just send it the whole file // GBA vba-next core will try to eat anything, regardless of size - if (Emulator is GBA || Emulator is VBANext || Emulator is MGBAHawk) + if (Emulator is VBANext || Emulator is MGBAHawk) { sram = File.ReadAllBytes(PathManager.SaveRamPath(Global.Game)); } @@ -1576,6 +1700,7 @@ namespace BizHawk.Client.EmuHawk // MessageBox.Show("Error: tried to load saveram, but core would not accept it?"); return; } + // why do we silently truncate\pad here instead of warning\erroring? sram = new byte[oldram.Length]; using (var reader = new BinaryReader( @@ -1620,10 +1745,12 @@ namespace BizHawk.Client.EmuHawk var writer = new BinaryWriter(new FileStream(path, FileMode.Create, FileAccess.Write)); var saveram = Emulator.AsSaveRam().CloneSaveRam(); - + if (saveram != null) + { writer.Write(saveram, 0, saveram.Length); - + } + writer.Close(); } } @@ -1649,12 +1776,7 @@ namespace BizHawk.Client.EmuHawk var system = ""; if (!Global.Game.IsNullInstance) { - //New Code - //We use SystemID as that has the system we are playing on. system = Emulator.SystemId; - //Old Code below. - //system = Global.Game.System; - } TI83SubMenu.Visible = false; @@ -1675,8 +1797,8 @@ namespace BizHawk.Client.EmuHawk AppleSubMenu.Visible = false; C64SubMenu.Visible = false; IntvSubMenu.Visible = false; - sNESToolStripMenuItem.Visible = false; virtualBoyToolStripMenuItem.Visible = false; + sNESToolStripMenuItem.Visible = false; switch (system) { @@ -1723,17 +1845,10 @@ namespace BizHawk.Client.EmuHawk case "SGB": if (Emulator is LibsnesCore) { - if ((Emulator as LibsnesCore).IsSGB) - { - SNESSubMenu.Text = "&SGB"; - } - else - { - SNESSubMenu.Text = "&SNES"; - } + SNESSubMenu.Text = ((LibsnesCore)Emulator).IsSGB ? "&SGB" : "&SNES"; SNESSubMenu.Visible = true; } - else if (Emulator is Emulation.Cores.Nintendo.SNES9X.Snes9x) + else if (Emulator is Snes9x) { sNESToolStripMenuItem.Visible = true; } @@ -1783,8 +1898,7 @@ namespace BizHawk.Client.EmuHawk } Global.ClientControls = controls; - Global.AutofireNullControls = new AutofireController(NullController.Instance.Definition, Emulator); - + _autofireNullControls = new AutofireController(NullController.Instance.Definition, Emulator); } private void LoadMoviesFromRecent(string path) @@ -1803,15 +1917,14 @@ namespace BizHawk.Client.EmuHawk private void LoadRomFromRecent(string rom) { - var ioa = OpenAdvancedSerializer.ParseWithLegacy(rom); - LoadRomArgs args = new LoadRomArgs() + var args = new LoadRomArgs { OpenAdvanced = ioa }; - //if(ioa is this or that) - for more complex behaviour + // if(ioa is this or that) - for more complex behaviour string romPath = ioa.SimplePath; if (!LoadRom(romPath, args)) @@ -1857,7 +1970,6 @@ namespace BizHawk.Client.EmuHawk // skips outputting the audio. There's also a third way which is when no throttle // method is selected, but the clock throttle determines that by itself and // everything appears normal here. - var rewind = Global.Rewinder.RewindActive && (Global.ClientControls["Rewind"] || PressRewind); var fastForward = Global.ClientControls["Fast Forward"] || FastForward; var turbo = IsTurboing; @@ -1875,7 +1987,8 @@ namespace BizHawk.Client.EmuHawk _throttle.SetCoreFps(Emulator.VsyncRate()); _throttle.signal_paused = EmulatorPaused; _throttle.signal_unthrottle = _unthrottled || turbo; - //zero 26-mar-2016 - vsync and vsync throttle here both is odd, but see comments elsewhere about triple buffering + + // zero 26-mar-2016 - vsync and vsync throttle here both is odd, but see comments elsewhere about triple buffering _throttle.signal_overrideSecondaryThrottle = (fastForward || rewind) && (Global.Config.SoundThrottle || Global.Config.VSyncThrottle || Global.Config.VSync); _throttle.SetSpeedPercent(speedPercent); } @@ -1912,15 +2025,16 @@ namespace BizHawk.Client.EmuHawk } } - void AutohideCursor(bool hide) + private void AutohideCursor(bool hide) { if (hide && !_cursorHidden) { if (_blankCursor == null) { - var ms = new System.IO.MemoryStream(BizHawk.Client.EmuHawk.Properties.Resources.BlankCursor); + var ms = new MemoryStream(Properties.Resources.BlankCursor); _blankCursor = new Cursor(ms); } + PresentationPanel.Control.Cursor = _blankCursor; _cursorHidden = true; } @@ -1952,9 +2066,8 @@ namespace BizHawk.Client.EmuHawk { return; } - //private Size _lastVideoSize = new Size(-1, -1), _lastVirtualSize = new Size(-1, -1); + var video = _currentVideoProvider; - //bool change = false; Size currVideoSize = new Size(video.BufferWidth, video.BufferHeight); Size currVirtualSize = new Size(video.VirtualWidth, video.VirtualHeight); if (currVideoSize != _lastVideoSize || currVirtualSize != _lastVirtualSize) @@ -1991,7 +2104,7 @@ namespace BizHawk.Client.EmuHawk var num = args.Length / 2; for (int i = 0; i < num; i++) { - sb.AppendFormat("{0} ({1})|{1}", args[i * 2], args[i * 2 + 1]); + sb.AppendFormat("{0} ({1})|{1}", args[i * 2], args[(i * 2) + 1]); if (i != num - 1) { sb.Append('|'); @@ -2109,8 +2222,7 @@ namespace BizHawk.Client.EmuHawk "No sync settings found, using currently configured settings for this core.", "No sync settings found", MessageBoxButtons.OK, - MessageBoxIcon.Warning - ); + MessageBoxIcon.Warning); } } } @@ -2118,7 +2230,6 @@ namespace BizHawk.Client.EmuHawk { e.Settings = Global.Config.GetCoreSyncSettings(e.Core); } - } private static void CoreSettings(object sender, RomLoader.SettingsLoadArgs e) @@ -2180,12 +2291,14 @@ namespace BizHawk.Client.EmuHawk } if (string.IsNullOrEmpty(path)) + { path = PathManager.DefaultIniPath; + } ConfigService.Save(path, Global.Config); } - private static void ToggleFPS() + private static void ToggleFps() { Global.Config.DisplayFPS ^= true; } @@ -2205,7 +2318,7 @@ namespace BizHawk.Client.EmuHawk Global.Config.DisplayInput ^= true; } - public static void ToggleSound() + private static void ToggleSound() { Global.Config.SoundEnabled ^= true; GlobalWin.Sound.StopSound(); @@ -2220,7 +2333,6 @@ namespace BizHawk.Client.EmuHawk Global.Config.SoundVolume = 100; } - //GlobalWin.Sound.ApplyVolumeSettings(); GlobalWin.OSD.AddMessage("Volume " + Global.Config.SoundVolume); } @@ -2232,7 +2344,6 @@ namespace BizHawk.Client.EmuHawk Global.Config.SoundVolume = 0; } - //GlobalWin.Sound.ApplyVolumeSettings(); GlobalWin.OSD.AddMessage("Volume " + Global.Config.SoundVolume); } @@ -2536,8 +2647,8 @@ namespace BizHawk.Client.EmuHawk } LedLightStatusLabel.Image = Emulator.AsDriveLight().DriveLightOn - ? StatusBarDiskLightOnImage - : StatusBarDiskLightOffImage; + ? _statusBarDiskLightOnImage + : _statusBarDiskLightOffImage; } else { @@ -2555,8 +2666,8 @@ namespace BizHawk.Client.EmuHawk } LinkConnectStatusBarButton.Image = Emulator.AsLinkable().LinkConnected - ? LinkCableOn - : LinkCableOff; + ? _linkCableOn + : _linkCableOff; } else { @@ -2602,16 +2713,10 @@ namespace BizHawk.Client.EmuHawk : "Background Input disabled"); } - private static void LimitFrameRateMessage() - { - GlobalWin.OSD.AddMessage(Global.Config.ClockThrottle ? "Framerate limiting on" : "Framerate limiting off"); - } - private static void VsyncMessage() { GlobalWin.OSD.AddMessage( - "Display Vsync set to " + (Global.Config.VSync ? "on" : "off") - ); + "Display Vsync set to " + (Global.Config.VSync ? "on" : "off")); } private static bool StateErrorAskUser(string title, string message) @@ -2620,8 +2725,7 @@ namespace BizHawk.Client.EmuHawk message, title, MessageBoxButtons.YesNo, - MessageBoxIcon.Question - ); + MessageBoxIcon.Question); return result == DialogResult.Yes; } @@ -2641,14 +2745,14 @@ namespace BizHawk.Client.EmuHawk }); } - private const int WM_DEVICECHANGE = 0x0219; + private const int WmDevicechange = 0x0219; // Alt key hacks protected override void WndProc(ref Message m) { switch (m.Msg) { - case WM_DEVICECHANGE: + case WmDevicechange: GamePad.Initialize(); GamePad360.Initialize(); break; @@ -2699,8 +2803,6 @@ namespace BizHawk.Client.EmuHawk UpdateKeyPriorityIcon(); switch (Global.Config.Input_Hotkey_OverrideOptions) { - default: - break; case 0: GlobalWin.OSD.AddMessage("Key priority set to Both Hotkey and Input"); break; @@ -2769,6 +2871,7 @@ namespace BizHawk.Client.EmuHawk if (Global.ClientControls["Frame Advance"] || PressFrameAdvance || HoldFrameAdvance) { _runloopFrameAdvance = true; + // handle the initial trigger of a frame advance if (_frameAdvanceTimestamp == 0) { @@ -2818,6 +2921,7 @@ namespace BizHawk.Client.EmuHawk { InitializeFpsData(); } + _lastFastForwardingOrRewinding = isFastForwardingOrRewinding; // client input-related duties @@ -2825,7 +2929,7 @@ namespace BizHawk.Client.EmuHawk Global.CheatList.Pulse(); - //zero 03-may-2014 - moved this before call to UpdateToolsBefore(), since it seems to clear the state which a lua event.framestart is going to want to alter + // zero 03-may-2014 - moved this before call to UpdateToolsBefore(), since it seems to clear the state which a lua event.framestart is going to want to alter Global.ClickyVirtualPadController.FrameTick(); Global.LuaAndAdaptor.FrameTick(); @@ -2857,9 +2961,13 @@ namespace BizHawk.Client.EmuHawk if (isFastForwardingOrRewinding) { if (Global.Config.SoundEnabledRWFF) + { atten *= Global.Config.SoundVolumeRWFF / 100.0f; + } else + { atten = 0; + } } // Mute if using Frame Advance/Frame Progress @@ -2871,9 +2979,12 @@ namespace BizHawk.Client.EmuHawk Global.MovieSession.HandleMovieOnFrameLoop(); - //why not skip audio if the user doesnt want sound + // why not skip audio if the user doesnt want sound bool renderSound = (Global.Config.SoundEnabled && !IsTurboing) || (_currAviWriter?.UsesAudio ?? false); - if (!renderSound) atten = 0; + if (!renderSound) + { + atten = 0; + } bool render = !_throttle.skipNextFrame || (_currAviWriter?.UsesVideo ?? false); Emulator.FrameAdvance(Global.ControllerOutput, render, renderSound); @@ -2892,7 +3003,7 @@ namespace BizHawk.Client.EmuHawk Global.CheatList.Pulse(); - if (!PauseAVI) + if (!PauseAvi) { AvFrameAdvance(); } @@ -2901,6 +3012,7 @@ namespace BizHawk.Client.EmuHawk { Global.AutoFireController.IncrementStarts(); } + Global.AutofireStickyXORAdapter.IncrementLoops(IsLagFrame); PressFrameAdvance = false; @@ -2927,9 +3039,11 @@ namespace BizHawk.Client.EmuHawk { TasMovieRecord record = (Global.MovieSession.Movie as TasMovie)[Emulator.Frame]; if (!record.Lagged.HasValue && IsSeeking) + { // haven't yet greenzoned the frame, hence it's after editing // then we want to pause here. taseditor fasion PauseEmulator(); + } } } @@ -2947,7 +3061,6 @@ namespace BizHawk.Client.EmuHawk if (Global.ClientControls["Rewind"] || PressRewind) { UpdateToolsAfter(); - //PressRewind = false; } GlobalWin.Sound.UpdateSound(atten); @@ -2970,28 +3083,31 @@ namespace BizHawk.Client.EmuHawk { _lastFps = (_lastFps + (_framesSinceLastFpsUpdate * _fpsSmoothing)) / (1.0 + (elapsedSeconds * _fpsSmoothing)); } + _framesSinceLastFpsUpdate = 0; _timestampLastFpsUpdate = currentTimestamp; - var fps_string = $"{_lastFps:0} fps"; + var fpsString = $"{_lastFps:0} fps"; if (isRewinding) { - fps_string += IsTurboing || isFastForwarding ? + fpsString += IsTurboing || isFastForwarding ? " <<<<" : " <<"; } else if (isFastForwarding) { - fps_string += IsTurboing ? + fpsString += IsTurboing ? " >>>>" : " >>"; } - GlobalWin.OSD.FPS = fps_string; + GlobalWin.OSD.FPS = fpsString; - //need to refresh window caption in this case + // need to refresh window caption in this case if (Global.Config.DispSpeedupFeatures == 0) + { SetWindowText(); + } } private void InitializeFpsData() @@ -3006,27 +3122,27 @@ namespace BizHawk.Client.EmuHawk #region AVI Stuff /// - /// start avi recording, unattended + /// start AVI recording, unattended /// - /// match the short name of an ivideowriter + /// match the short name of an /// filename to save to private void RecordAv(string videowritername, string filename) { - _RecordAv(videowritername, filename, true); + RecordAvBase(videowritername, filename, true); } /// - /// start avi recording, asking user for filename and options + /// start AV recording, asking user for filename and options /// private void RecordAv() { - _RecordAv(null, null, false); + RecordAvBase(null, null, false); } /// /// start AV recording /// - private void _RecordAv(string videowritername, string filename, bool unattended) + private void RecordAvBase(string videowritername, string filename, bool unattended) { if (_currAviWriter != null) { @@ -3034,10 +3150,12 @@ namespace BizHawk.Client.EmuHawk } // select IVideoWriter to use - IVideoWriter aw = null; + IVideoWriter aw; if (string.IsNullOrEmpty(videowritername) && !string.IsNullOrEmpty(Global.Config.VideoWriter)) + { videowritername = Global.Config.VideoWriter; + } if (unattended && !string.IsNullOrEmpty(videowritername)) { @@ -3059,7 +3177,7 @@ namespace BizHawk.Client.EmuHawk try { - bool usingAvi = aw is AviWriter; //SO GROSS! + bool usingAvi = aw is AviWriter; // SO GROSS! if (_dumpaudiosync) { @@ -3090,10 +3208,12 @@ namespace BizHawk.Client.EmuHawk } else { - //THIS IS REALLY SLOPPY! - //PLEASE REDO ME TO NOT CARE WHICH AVWRITER IS USED! - if(usingAvi && !string.IsNullOrEmpty(Global.Config.AVICodecToken)) + // THIS IS REALLY SLOPPY! + // PLEASE REDO ME TO NOT CARE WHICH AVWRITER IS USED! + if (usingAvi && !string.IsNullOrEmpty(Global.Config.AVICodecToken)) + { aw.SetDefaultVideoCodecToken(); + } var token = aw.AcquireVideoCodecToken(this); if (token == null) @@ -3116,7 +3236,7 @@ namespace BizHawk.Client.EmuHawk string ext = aw.DesiredExtension(); string pathForOpenFile; - //handle directories first + // handle directories first if (ext == "") { var fbd = new FolderBrowserEx(); @@ -3125,6 +3245,7 @@ namespace BizHawk.Client.EmuHawk aw.Dispose(); return; } + pathForOpenFile = fbd.SelectedPath; } else @@ -3132,7 +3253,7 @@ namespace BizHawk.Client.EmuHawk var sfd = new SaveFileDialog(); if (Global.Game != null) { - sfd.FileName = PathManager.FilesystemSafeName(Global.Game) + "." + ext; //dont use Path.ChangeExtension, it might wreck game names with dots in them + sfd.FileName = PathManager.FilesystemSafeName(Global.Game) + "." + ext; // dont use Path.ChangeExtension, it might wreck game names with dots in them sfd.InitialDirectory = PathManager.MakeAbsolutePath(Global.Config.PathEntries.AvPathFragment, null); } else @@ -3187,6 +3308,7 @@ namespace BizHawk.Client.EmuHawk _aviSoundInputAsync = new SyncToAsyncProvider(_currentSoundProvider); } } + _dumpProxy = new SimpleSyncSoundProvider(); RewireSound(); } @@ -3236,14 +3358,16 @@ namespace BizHawk.Client.EmuHawk { if (_currAviWriter != null) { - //TODO ZERO - this code is pretty jacked. we'll want to frugalize buffers better for speedier dumping, and we might want to rely on the GL layer for padding + // TODO ZERO - this code is pretty jacked. we'll want to frugalize buffers better for speedier dumping, and we might want to rely on the GL layer for padding try { - //is this the best time to handle this? or deeper inside? + // is this the best time to handle this? or deeper inside? if (_currAviWriterFrameList != null) { if (!_currAviWriterFrameList.Contains(Emulator.Frame)) + { goto HANDLE_AUTODUMP; + } } IVideoProvider output; @@ -3252,21 +3376,15 @@ namespace BizHawk.Client.EmuHawk { BitmapBuffer bbin = null; Bitmap bmpin = null; - Bitmap bmpout = null; try { - if (Global.Config.AVI_CaptureOSD) - { - bbin = CaptureOSD(); - } - else - { - bbin = new BitmapBuffer(_currentVideoProvider.BufferWidth, _currentVideoProvider.BufferHeight, _currentVideoProvider.GetVideoBuffer()); - } + bbin = Global.Config.AVI_CaptureOSD + ? CaptureOSD() + : new BitmapBuffer(_currentVideoProvider.BufferWidth, _currentVideoProvider.BufferHeight, _currentVideoProvider.GetVideoBuffer()); bbin.DiscardAlpha(); - bmpout = new Bitmap(_avwriterResizew, _avwriterResizeh, PixelFormat.Format32bppArgb); + var bmpout = new Bitmap(_avwriterResizew, _avwriterResizeh, PixelFormat.Format32bppArgb); bmpin = bbin.ToSysdrawingBitmap(); using (var g = Graphics.FromImage(bmpout)) { @@ -3288,8 +3406,8 @@ namespace BizHawk.Client.EmuHawk } finally { - if (bbin != null) bbin.Dispose(); - if (bmpin != null) bmpin.Dispose(); + bbin?.Dispose(); + bmpin?.Dispose(); } } else @@ -3300,7 +3418,9 @@ namespace BizHawk.Client.EmuHawk disposableOutput = (IDisposable)output; } else + { output = _currentVideoProvider; + } } _currAviWriter.SetFrame(Emulator.Frame); @@ -3309,17 +3429,14 @@ namespace BizHawk.Client.EmuHawk int nsamp; if (_dumpaudiosync) { - (_currAviWriter as VideoStretcher).DumpAV(output, _currentSoundProvider, out samp, out nsamp); + ((VideoStretcher)_currAviWriter).DumpAV(output, _currentSoundProvider, out samp, out nsamp); } else { - (_currAviWriter as AudioStretcher).DumpAV(output, _aviSoundInputAsync, out samp, out nsamp); + ((AudioStretcher)_currAviWriter).DumpAV(output, _aviSoundInputAsync, out samp, out nsamp); } - if (disposableOutput != null) - { - disposableOutput.Dispose(); - } + disposableOutput?.Dispose(); _dumpProxy.PutSamples(samp, nsamp); } @@ -3352,10 +3469,8 @@ namespace BizHawk.Client.EmuHawk { return ac.SelectedMemberIndex; } - else - { - return null; - } + + return null; } #endregion @@ -3384,7 +3499,7 @@ namespace BizHawk.Client.EmuHawk // Retry loading the ROM here. This leads to recursion, as the original call to LoadRom has not exited yet, // but unless the user tries and fails to set his firmware a lot of times, nothing should happen. // Refer to how RomLoader implemented its LoadRom method for a potential fix on this. - LoadRom(e.RomPath, CurrentLoadRomArgs); + LoadRom(e.RomPath, _currentLoadRomArgs); } } } @@ -3418,46 +3533,46 @@ namespace BizHawk.Client.EmuHawk public class LoadRomArgs { - public bool? Deterministic; - public IOpenAdvanced OpenAdvanced; + public bool? Deterministic { get; set; } + public IOpenAdvanced OpenAdvanced { get; set; } } - LoadRomArgs CurrentLoadRomArgs; + private LoadRomArgs _currentLoadRomArgs; // Still needs a good bit of refactoring public bool LoadRom(string path, LoadRomArgs args) { path = HawkFile.Util_ResolveLink(path); - //default args - if (args == null) args = new LoadRomArgs(); + // default args + if (args == null) + { + args = new LoadRomArgs(); + } - //if this is the first call to LoadRom (they will come in recursively) then stash the args + // if this is the first call to LoadRom (they will come in recursively) then stash the args bool firstCall = false; - if (CurrentLoadRomArgs == null) + if (_currentLoadRomArgs == null) { firstCall = true; - CurrentLoadRomArgs = args; + _currentLoadRomArgs = args; } else { - args = CurrentLoadRomArgs; + args = _currentLoadRomArgs; } try { // If deterministic emulation is passed in, respect that value regardless, else determine a good value (currently that simply means movies require deterministic emulaton) - bool deterministic = args.Deterministic.HasValue ? - args.Deterministic.Value : - Global.MovieSession.QueuedMovie != null; - //Global.MovieSession.Movie.IsActive; + bool deterministic = args.Deterministic ?? Global.MovieSession.QueuedMovie != null; if (!GlobalWin.Tools.AskSave()) { return false; } - bool asLibretro = (args.OpenAdvanced is OpenAdvanced_Libretro || args.OpenAdvanced is OpenAdvanced_LibretroNoGame); + bool asLibretro = args.OpenAdvanced is OpenAdvanced_Libretro || args.OpenAdvanced is OpenAdvanced_LibretroNoGame; var loader = new RomLoader { @@ -3481,32 +3596,43 @@ namespace BizHawk.Client.EmuHawk var nextComm = CreateCoreComm(); - //we need to inform LoadRom which Libretro core to use... + // we need to inform LoadRom which Libretro core to use... IOpenAdvanced ioa = args.OpenAdvanced; if (ioa is IOpenAdvancedLibretro) { - var ioaretro = ioa as IOpenAdvancedLibretro; + var ioaretro = (IOpenAdvancedLibretro)ioa; + + // prepare a core specification + // if it wasnt already specified, use the current default + if (ioaretro.CorePath == null) + { + ioaretro.CorePath = Global.Config.LibretroCore; + } - //prepare a core specification - //if it wasnt already specified, use the current default - if (ioaretro.CorePath == null) ioaretro.CorePath = Global.Config.LibretroCore; nextComm.LaunchLibretroCore = ioaretro.CorePath; if (nextComm.LaunchLibretroCore == null) + { throw new InvalidOperationException("Can't load a file via Libretro until a core is specified"); + } } CoreFileProvider.SyncCoreCommInputSignals(nextComm); var result = loader.LoadRom(path, nextComm); - //we need to replace the path in the OpenAdvanced with the canonical one the user chose. - //It can't be done until loder.LoadRom happens (for CanonicalFullPath) - //i'm not sure this needs to be more abstractly engineered yet until we have more OpenAdvanced examples + // we need to replace the path in the OpenAdvanced with the canonical one the user chose. + // It can't be done until loder.LoadRom happens (for CanonicalFullPath) + // i'm not sure this needs to be more abstractly engineered yet until we have more OpenAdvanced examples if (ioa is OpenAdvanced_Libretro) { var oaretro = ioa as OpenAdvanced_Libretro; oaretro.token.Path = loader.CanonicalFullPath; } - if (ioa is OpenAdvanced_OpenRom) ((OpenAdvanced_OpenRom)ioa).Path = loader.CanonicalFullPath; + + if (ioa is OpenAdvanced_OpenRom) + { + ((OpenAdvanced_OpenRom)ioa).Path = loader.CanonicalFullPath; + } + string loaderName = "*" + OpenAdvancedSerializer.Serialize(ioa); if (result) @@ -3523,7 +3649,7 @@ namespace BizHawk.Client.EmuHawk if (loader.LoadedEmulator is NES) { - var nes = loader.LoadedEmulator as NES; + var nes = (NES)loader.LoadedEmulator; if (!string.IsNullOrWhiteSpace(nes.GameName)) { Global.Game.Name = nes.GameName; @@ -3533,11 +3659,12 @@ namespace BizHawk.Client.EmuHawk } else if (loader.LoadedEmulator is QuickNES) { - var qns = loader.LoadedEmulator as QuickNES; + var qns = (QuickNES)loader.LoadedEmulator; if (!string.IsNullOrWhiteSpace(qns.BootGodName)) { Global.Game.Name = qns.BootGodName; } + if (qns.BootGodStatus.HasValue) { Global.Game.Status = qns.BootGodStatus.Value; @@ -3546,11 +3673,7 @@ namespace BizHawk.Client.EmuHawk if (Emulator.CoreComm.RomStatusDetails == null && loader.Rom != null) { - Emulator.CoreComm.RomStatusDetails = string.Format( - "{0}\r\nSHA1:{1}\r\nMD5:{2}\r\n", - loader.Game.Name, - loader.Rom.RomData.HashSHA1(), - loader.Rom.RomData.HashMD5()); + Emulator.CoreComm.RomStatusDetails = $"{loader.Game.Name}\r\nSHA1:{loader.Rom.RomData.HashSHA1()}\r\nMD5:{loader.Rom.RomData.HashMD5()}\r\n"; } if (Emulator.HasBoardInfo()) @@ -3590,7 +3713,7 @@ namespace BizHawk.Client.EmuHawk } SetWindowText(); - CurrentlyOpenRomPoopForAdvancedLoaderPleaseRefactorME = loaderName; + _currentlyOpenRomPoopForAdvancedLoaderPleaseRefactorMe = loaderName; CurrentlyOpenRom = loaderName.Replace("*OpenRom*", ""); // POOP HandlePlatformMenus(); _stateSlots.Clear(); @@ -3620,18 +3743,19 @@ namespace BizHawk.Client.EmuHawk Console.WriteLine(" {0} : {1}", f.FirmwareId, f.Hash); } } - ApiHawk.ClientApi.OnRomLoaded(); + + ClientApi.OnRomLoaded(); return true; } else { - //This shows up if there's a problem + // This shows up if there's a problem // TODO: put all these in a single method or something - //The ROM has been loaded by a recursive invocation of the LoadROM method. + // The ROM has been loaded by a recursive invocation of the LoadROM method. if (!(Emulator is NullEmulator)) { - ApiHawk.ClientApi.OnRomLoaded(); + ClientApi.OnRomLoaded(); return true; } @@ -3649,12 +3773,12 @@ namespace BizHawk.Client.EmuHawk { if (firstCall) { - CurrentLoadRomArgs = null; + _currentLoadRomArgs = null; } } } - private string CurrentlyOpenRomPoopForAdvancedLoaderPleaseRefactorME = ""; + private string _currentlyOpenRomPoopForAdvancedLoaderPleaseRefactorMe = ""; private void CommitCoreSettingsToConfig() { @@ -3700,13 +3824,15 @@ namespace BizHawk.Client.EmuHawk CommitCoreSettingsToConfig(); if (Global.MovieSession.Movie.IsActive) // Note: this must be called after CommitCoreSettingsToConfig() { - StopMovie(true); + StopMovie(); } Global.Rewinder.Uninitialize(); if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.Get().Restart(); + } Global.CheatList.SaveOnClose(); Emulator.Dispose(); @@ -3714,18 +3840,18 @@ namespace BizHawk.Client.EmuHawk CoreFileProvider.SyncCoreCommInputSignals(coreComm); Emulator = new NullEmulator(coreComm, Global.Config.GetCoreSettings()); Global.ActiveController = new Controller(NullController.Instance.Definition); - Global.AutoFireController = Global.AutofireNullControls; + Global.AutoFireController = _autofireNullControls; RewireSound(); RebootStatusBarIcon.Visible = false; GameIsClosing = false; } - public bool GameIsClosing { get; set; } // Lets tools make better decisions when being called by CloseGame + public bool GameIsClosing { get; private set; } // Lets tools make better decisions when being called by CloseGame public void CloseRom(bool clearSram = false) { - //This gets called after Close Game gets called. - //Tested with NESHawk and SMB3 (U) + // This gets called after Close Game gets called. + // Tested with NESHawk and SMB3 (U) if (GlobalWin.Tools.AskSave()) { CloseGame(clearSram); @@ -3816,7 +3942,9 @@ namespace BizHawk.Client.EmuHawk bool wasCountingRerecords = Global.MovieSession.Movie.IsCountingRerecords; if (fromLua) + { Global.MovieSession.Movie.IsCountingRerecords = false; + } if (SavestateManager.LoadStateFile(path, userFriendlyStateName)) { @@ -3908,6 +4036,7 @@ namespace BizHawk.Client.EmuHawk { GlobalWin.OSD.AddMessage("Unable to save state " + path); } + if (!fromLua) { UpdateStatusSlots(); @@ -3924,7 +4053,7 @@ namespace BizHawk.Client.EmuHawk bool handled; ClientApi.OnBeforeQuickSave(this, quickSlotName, out handled); - if(handled) + if (handled) { return; } @@ -3945,7 +4074,9 @@ namespace BizHawk.Client.EmuHawk // Make backup first if (Global.Config.BackupSavestates) - BizHawk.Common.Util.TryMoveBackupFile(path, path + ".bak"); + { + Util.TryMoveBackupFile(path, path + ".bak"); + } SaveState(path, quickSlotName, false); @@ -3965,7 +4096,9 @@ namespace BizHawk.Client.EmuHawk // allow named state export for tastudio, since it's safe, unlike loading one // todo: make it not save laglog in that case if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.NamedStatePending = true; + } if (IsSavestateSlave) { @@ -3997,7 +4130,9 @@ namespace BizHawk.Client.EmuHawk } if (GlobalWin.Tools.IsLoaded()) + { GlobalWin.Tools.TAStudio.NamedStatePending = false; + } } private void LoadStateAs() @@ -4126,7 +4261,7 @@ namespace BizHawk.Client.EmuHawk } } - public void StopMovie(bool saveChanges = true) + private void StopMovie(bool saveChanges = true) { if (IsSlave && Master.WantsToControlStopMovie) { @@ -4157,6 +4292,16 @@ namespace BizHawk.Client.EmuHawk } } + private void preferencesToolStripMenuItem1_Click(object sender, EventArgs e) + { + GenericCoreConfig.DoDialog(this, "VirtualBoy Settings"); + } + + private void preferencesToolStripMenuItem_Click(object sender, EventArgs e) + { + GenericCoreConfig.DoDialog(this, "Snes9x Settings"); + } + private bool Rewind(ref bool runFrame, long currentTimestamp, out bool returnToRecording) { var isRewinding = false; @@ -4178,15 +4323,25 @@ namespace BizHawk.Client.EmuHawk double timestampDeltaMs = (double)(currentTimestamp - _frameRewindTimestamp) / Stopwatch.Frequency * 1000.0; isRewinding = timestampDeltaMs >= Global.Config.FrameProgressDelayMs; - //clear this flag once we get out of the progress stage + // clear this flag once we get out of the progress stage if (isRewinding) + { _frameRewindWasPaused = false; + } - //if we're freely running, there's no need for reverse frame progress semantics (that may be debateable though) - if (!EmulatorPaused) isRewinding = true; + // if we're freely running, there's no need for reverse frame progress semantics (that may be debateable though) + if (!EmulatorPaused) + { + isRewinding = true; + } if (_frameRewindWasPaused) - if (IsSeeking) isRewinding = false; + { + if (IsSeeking) + { + isRewinding = false; + } + } } if (isRewinding) @@ -4243,61 +4398,5 @@ namespace BizHawk.Client.EmuHawk } #endregion - - private void FeaturesMenuItem_Click(object sender, EventArgs e) - { - GlobalWin.Tools.Load(); - } - - private void BasicBotMenuItem_Click(object sender, EventArgs e) - { - GlobalWin.Tools.Load(); - } - - private void DisplayMessagesMenuItem_Click(object sender, EventArgs e) - { - Global.Config.DisplayMessages ^= true; - } - - private void gameSharkConverterToolStripMenuItem_Click(object sender, EventArgs e) - { - GlobalWin.Tools.Load(); - } - - private void HelpSubMenu_DropDownOpened(object sender, EventArgs e) - { - FeaturesMenuItem.Visible = VersionInfo.DeveloperBuild; - } - - private void SNESControllerConfigurationMenuItem_Click(object sender, EventArgs e) - { - new SNESControllerSettings().ShowDialog(); - } - - private void preferencesToolStripMenuItem_Click(object sender, EventArgs e) - { - GenericCoreConfig.DoDialog(this, "Snes9x settings"); - } - - private void preferencesToolStripMenuItem1_Click(object sender, EventArgs e) - { - GenericCoreConfig.DoDialog(this, "VirtualBoy Settings"); - } - - private void CreateMultigameFileMenuItem_Click(object sender, EventArgs e) - { - GlobalWin.Tools.Load(); - } - - private void coreToolStripMenuItem_DropDownOpened(object sender, EventArgs e) - { - quickNESToolStripMenuItem.Checked = Global.Config.NES_InQuickNES; - nesHawkToolStripMenuItem.Checked = !Global.Config.NES_InQuickNES; - } - - private void allowGameDBCoreOverridesToolStripMenuItem_Click(object sender, EventArgs e) - { - Global.Config.CoreForcingViaGameDB ^= true; - } } } diff --git a/BizHawk.Client.EmuHawk/Program.cs b/BizHawk.Client.EmuHawk/Program.cs index 57fd3accc5..4a32459c5a 100644 --- a/BizHawk.Client.EmuHawk/Program.cs +++ b/BizHawk.Client.EmuHawk/Program.cs @@ -121,7 +121,7 @@ namespace BizHawk.Client.EmuHawk BizHawk.Client.Common.StringLogUtil.DefaultToDisk = Global.Config.MoviesOnDisk; BizHawk.Client.Common.StringLogUtil.DefaultToAWE = Global.Config.MoviesInAWE; - //super hacky! this needs to be done first. still not worth the trouble to make this system fully proper + // super hacky! this needs to be done first. still not worth the trouble to make this system fully proper for (int i = 0; i < args.Length; i++) { var arg = args[i].ToLower(); @@ -131,13 +131,12 @@ namespace BizHawk.Client.EmuHawk } } - //create IGL context. we do this whether or not the user has selected OpenGL, so that we can run opengl-based emulator cores + // create IGL context. we do this whether or not the user has selected OpenGL, so that we can run opengl-based emulator cores GlobalWin.IGL_GL = new Bizware.BizwareGL.Drivers.OpenTK.IGL_TK(2, 0, false); - //setup the GL context manager, needed for coping with multiple opengl cores vs opengl display method + // setup the GL context manager, needed for coping with multiple opengl cores vs opengl display method GLManager.CreateInstance(GlobalWin.IGL_GL); GlobalWin.GLManager = GLManager.Instance; - GlobalWin.CR_GL = GlobalWin.GLManager.GetContextForIGL(GlobalWin.GL); //now create the "GL" context for the display method. we can reuse the IGL_TK context if opengl display method is chosen REDO_DISPMETHOD: @@ -153,7 +152,8 @@ namespace BizHawk.Client.EmuHawk { var e2 = new Exception("Initialization of Direct3d 9 Display Method failed; falling back to GDI+", ex); new ExceptionBox(e2).ShowDialog(); - //fallback + + // fallback Global.Config.DispMethod = Config.EDispMethod.GdiPlus; goto REDO_DISPMETHOD; } @@ -161,17 +161,18 @@ namespace BizHawk.Client.EmuHawk else { GlobalWin.GL = GlobalWin.IGL_GL; - //check the opengl version and dont even try to boot this crap up if its too old + + // check the opengl version and dont even try to boot this crap up if its too old int version = GlobalWin.IGL_GL.Version; if (version < 200) { - //fallback + // fallback Global.Config.DispMethod = Config.EDispMethod.GdiPlus; goto REDO_DISPMETHOD; } } - //try creating a GUI Renderer. If that doesn't succeed. we fallback + // try creating a GUI Renderer. If that doesn't succeed. we fallback try { using (GlobalWin.GL.CreateRenderer()) { } diff --git a/BizHawk.Client.EmuHawk/Properties/Resources.Designer.cs b/BizHawk.Client.EmuHawk/Properties/Resources.Designer.cs index a5d0f207dd..08544fa997 100644 --- a/BizHawk.Client.EmuHawk/Properties/Resources.Designer.cs +++ b/BizHawk.Client.EmuHawk/Properties/Resources.Designer.cs @@ -900,16 +900,6 @@ namespace BizHawk.Client.EmuHawk.Properties { } } - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap meteor { - get { - object obj = ResourceManager.GetObject("meteor", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - /// /// Looks up a localized resource of type System.Drawing.Bitmap. /// diff --git a/BizHawk.Client.EmuHawk/Properties/Resources.resx b/BizHawk.Client.EmuHawk/Properties/Resources.resx index e4f374957f..54487806a0 100644 --- a/BizHawk.Client.EmuHawk/Properties/Resources.resx +++ b/BizHawk.Client.EmuHawk/Properties/Resources.resx @@ -1041,9 +1041,6 @@ ..\images\tastudio\ts_v_piano_04_green_blue.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - ..\images\meteor.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - ..\images\HotKeys.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a diff --git a/BizHawk.Client.EmuHawk/images/meteor.png b/BizHawk.Client.EmuHawk/images/meteor.png deleted file mode 100644 index 8ddc63696c..0000000000 Binary files a/BizHawk.Client.EmuHawk/images/meteor.png and /dev/null differ diff --git a/BizHawk.Client.EmuHawk/tools/Debugger/AddBreakpointDialog.cs b/BizHawk.Client.EmuHawk/tools/Debugger/AddBreakpointDialog.cs index 48b117c8f1..cddd4317d4 100644 --- a/BizHawk.Client.EmuHawk/tools/Debugger/AddBreakpointDialog.cs +++ b/BizHawk.Client.EmuHawk/tools/Debugger/AddBreakpointDialog.cs @@ -1,10 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Emulation.Common; @@ -21,7 +15,8 @@ namespace BizHawk.Client.EmuHawk AddressMask = 0xFFFFFFFF; } - public AddBreakpointDialog(BreakpointOperation op, uint address, uint mask, MemoryCallbackType type):this(op) + public AddBreakpointDialog(BreakpointOperation op, uint address, uint mask, MemoryCallbackType type) + : this(op) { AddressMaskBox.SetHexProperties(0xFFFFFFFF); Address = address; @@ -37,6 +32,7 @@ namespace BizHawk.Client.EmuHawk { return _operation; } + set { switch (value) @@ -51,6 +47,7 @@ namespace BizHawk.Client.EmuHawk Text = "Edit Breakpoint"; break; } + _operation = value; } } @@ -63,7 +60,6 @@ namespace BizHawk.Client.EmuHawk } ExecuteRadio.Enabled = false; - } public MemoryCallbackType BreakType @@ -124,6 +120,7 @@ namespace BizHawk.Client.EmuHawk { return AddressBox.GetMax(); } + set { AddressBox.SetHexProperties(value); @@ -145,13 +142,11 @@ namespace BizHawk.Client.EmuHawk private void AddBreakpointDialog_Load(object sender, EventArgs e) { - } public enum BreakpointOperation { Add, Edit, Duplicate } - } } diff --git a/BizHawk.Client.EmuHawk/tools/Debugger/Breakpoint.cs b/BizHawk.Client.EmuHawk/tools/Debugger/Breakpoint.cs index 07ac3fb0f3..cd0fd84795 100644 --- a/BizHawk.Client.EmuHawk/tools/Debugger/Breakpoint.cs +++ b/BizHawk.Client.EmuHawk/tools/Debugger/Breakpoint.cs @@ -1,8 +1,7 @@ -using BizHawk.Emulation.Common; -using System; +using System; using System.Collections.Generic; -using System.Linq; -using System.Text; + +using BizHawk.Emulation.Common; namespace BizHawk.Client.EmuHawk { @@ -34,6 +33,7 @@ namespace BizHawk.Client.EmuHawk breakpoint.ReadOnly = false; breakpoint.Active = false; } + return base.Remove(b); } @@ -59,6 +59,7 @@ namespace BizHawk.Client.EmuHawk removeCount++; } } + return removeCount; } } @@ -106,11 +107,11 @@ namespace BizHawk.Client.EmuHawk ReadOnly = readOnly; } - public Action Callback { get; set; } + public Action Callback { get; } public uint? Address { get; set; } public uint? AddressMask { get; set; } public MemoryCallbackType Type { get; set; } - public string Name { get; set; } + public string Name { get; } internal bool ReadOnly { get; set; } diff --git a/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.Designer.cs b/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.Designer.cs index 3d9e4f4711..a30300fc04 100644 --- a/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.Designer.cs +++ b/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.Designer.cs @@ -1,4 +1,4 @@ -namespace BizHawk.Client.EmuHawk.tools.Debugger +namespace BizHawk.Client.EmuHawk { partial class BreakpointControl { diff --git a/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.cs b/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.cs index cc3fca90a3..0142a6e579 100644 --- a/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.cs +++ b/BizHawk.Client.EmuHawk/tools/Debugger/BreakpointControl.cs @@ -1,19 +1,14 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Common.NumberExtensions; using BizHawk.Emulation.Common; -using BizHawk.Emulation.Common.IEmulatorExtensions; -using BizHawk.Client.Common; using BizHawk.Client.EmuHawk.WinFormExtensions; -namespace BizHawk.Client.EmuHawk.tools.Debugger +namespace BizHawk.Client.EmuHawk { public partial class BreakpointControl : UserControl { @@ -21,7 +16,8 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger public IMemoryCallbackSystem MCS { get; set; } public GenericDebugger ParentDebugger { get; set; } public IMemoryDomains MemoryDomains { get; set; } - private readonly BreakpointList Breakpoints = new BreakpointList(); + + private readonly BreakpointList _breakpoints = new BreakpointList(); public BreakpointControl() { @@ -29,7 +25,7 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger BreakpointView.QueryItemText += BreakPointView_QueryItemText; BreakpointView.QueryItemBkColor += BreakPointView_QueryItemBkColor; BreakpointView.VirtualMode = true; - Breakpoints.Callback = BreakpointCallback; + _breakpoints.Callback = BreakpointCallback; } private void BreakpointControl_Load(object sender, EventArgs e) @@ -43,24 +39,24 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger switch (column) { case 0: - text = string.Format("{0:X}", Breakpoints[index].Address); + text = $"{_breakpoints[index].Address:X}"; break; case 1: - text = string.Format("{0:X}", Breakpoints[index].AddressMask); + text = $"{_breakpoints[index].AddressMask:X}"; break; case 2: - text = Breakpoints[index].Type.ToString(); + text = _breakpoints[index].Type.ToString(); break; case 3: - text = Breakpoints[index].Name; + text = _breakpoints[index].Name; break; } } private void BreakPointView_QueryItemBkColor(int index, int column, ref Color color) { - color = Breakpoints[index].ReadOnly ? SystemColors.Control - : Breakpoints[index].Active ? Color.LightCyan + color = _breakpoints[index].ReadOnly ? SystemColors.Control + : _breakpoints[index].Active ? Color.LightCyan : Color.White; } @@ -75,11 +71,11 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger { BreakpointCallback(); - var seekBreakpoint = Breakpoints.FirstOrDefault(x => x.Name.StartsWith(SeekName)); + var seekBreakpoint = _breakpoints.FirstOrDefault(x => x.Name.StartsWith(SeekName)); if (seekBreakpoint != null) { - Breakpoints.Remove(seekBreakpoint); + _breakpoints.Remove(seekBreakpoint); UpdateValues(); } @@ -94,30 +90,26 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger { CheckForNewBreakpoints(); - BreakpointView.ItemCount = Breakpoints.Count; + BreakpointView.ItemCount = _breakpoints.Count; UpdateStatsLabel(); } } - /// - /// Did any breakpoints get added from other sources such as lua? - /// + // Did any breakpoints get added from other sources such as lua? private void CheckForNewBreakpoints() { - if (MCS != null) { foreach (var callback in MCS) { - if (!Breakpoints.Any(b => + if (!_breakpoints.Any(b => b.Type == callback.Type && b.Address == callback.Address && b.AddressMask == callback.AddressMask && b.Name == callback.Name && - b.Callback == callback.Callback - )) + b.Callback == callback.Callback)) { - Breakpoints.Add(new Breakpoint(Core, callback)); + _breakpoints.Add(new Breakpoint(Core, callback)); } } } @@ -129,32 +121,32 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger { foreach (var callback in MCS) { - Breakpoints.Add(new Breakpoint(Core, callback)); + _breakpoints.Add(new Breakpoint(Core, callback)); } - BreakpointView.ItemCount = Breakpoints.Count; + BreakpointView.ItemCount = _breakpoints.Count; BreakpointView.Refresh(); UpdateBreakpointRemoveButton(); UpdateStatsLabel(); } else { - this.Enabled = false; + Enabled = false; ParentDebugger.DisableBreakpointBox(); } } public void Shutdown() { - Breakpoints.Clear(); + _breakpoints.Clear(); UpdateStatsLabel(); } public void AddBreakpoint(uint address, uint mask, MemoryCallbackType type) { - Breakpoints.Add(Core, address, mask, type); + _breakpoints.Add(Core, address, mask, type); - BreakpointView.ItemCount = Breakpoints.Count; + BreakpointView.ItemCount = _breakpoints.Count; UpdateBreakpointRemoveButton(); UpdateStatsLabel(); } @@ -165,10 +157,10 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger if (b.ShowHawkDialog() == DialogResult.OK) { - Breakpoints.Add(Core, b.Address, b.AddressMask, b.BreakType); + _breakpoints.Add(Core, b.Address, b.AddressMask, b.BreakType); } - BreakpointView.ItemCount = Breakpoints.Count; + BreakpointView.ItemCount = _breakpoints.Count; UpdateBreakpointRemoveButton(); UpdateStatsLabel(); } @@ -177,29 +169,26 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger public void AddSeekBreakpoint(uint pcVal, int pcBitSize) { - var Name = SeekName + pcVal.ToHexString(pcBitSize / 4); - Breakpoints.Add(new Breakpoint(Name, true, Core, SeekCallback, pcVal, 0xFFFFFFFF, MemoryCallbackType.Execute)); + var name = SeekName + pcVal.ToHexString(pcBitSize / 4); + _breakpoints.Add(new Breakpoint(name, true, Core, SeekCallback, pcVal, 0xFFFFFFFF, MemoryCallbackType.Execute)); } public void RemoveCurrentSeek() { - var seekBreakpoint = Breakpoints.FirstOrDefault(x => x.Name.StartsWith(SeekName)); + var seekBreakpoint = _breakpoints.FirstOrDefault(x => x.Name.StartsWith(SeekName)); if (seekBreakpoint != null) { - Breakpoints.Remove(seekBreakpoint); + _breakpoints.Remove(seekBreakpoint); UpdateValues(); } } - private IEnumerable SelectedIndices - { - get { return BreakpointView.SelectedIndices.Cast(); } - } + private IEnumerable SelectedIndices => BreakpointView.SelectedIndices.Cast(); - private IEnumerable SelectedItems + private IEnumerable SelectedItems { - get { return SelectedIndices.Select(index => Breakpoints[index]); } + get { return SelectedIndices.Select(index => _breakpoints[index]); } } private IEnumerable EditableItems @@ -216,10 +205,10 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger { foreach (var item in items) { - Breakpoints.Remove(item); + _breakpoints.Remove(item); } - BreakpointView.ItemCount = Breakpoints.Count; + BreakpointView.ItemCount = _breakpoints.Count; UpdateBreakpointRemoveButton(); UpdateStatsLabel(); } @@ -254,7 +243,7 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger item.Active ^= true; } - BreakpointView.ItemCount = Breakpoints.Count; + BreakpointView.ItemCount = _breakpoints.Count; UpdateBreakpointRemoveButton(); UpdateStatsLabel(); } @@ -271,7 +260,7 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger private void UpdateStatsLabel() { - BreakpointStatsLabel.Text = string.Format("{0} Total / {1} Active", Breakpoints.Count(), Breakpoints.Count(x => x.Active)); + BreakpointStatsLabel.Text = $"{_breakpoints.Count} Total / {_breakpoints.Count(b => b.Active)} Active"; } private void ToggleButton_Click(object sender, EventArgs e) @@ -281,7 +270,7 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger item.Active ^= true; } - BreakpointView.ItemCount = Breakpoints.Count; + BreakpointView.ItemCount = _breakpoints.Count; UpdateStatsLabel(); } @@ -295,11 +284,11 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger if (b.ShowHawkDialog() == DialogResult.OK) { - Breakpoints.Add(new Breakpoint(Core, breakpoint.Callback, b.Address, b.AddressMask, b.BreakType, breakpoint.Active)); + _breakpoints.Add(new Breakpoint(Core, breakpoint.Callback, b.Address, b.AddressMask, b.BreakType, breakpoint.Active)); } } - BreakpointView.ItemCount = Breakpoints.Count; + BreakpointView.ItemCount = _breakpoints.Count; UpdateBreakpointRemoveButton(); UpdateStatsLabel(); } @@ -321,7 +310,7 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger } } - BreakpointView.ItemCount = Breakpoints.Count; + BreakpointView.ItemCount = _breakpoints.Count; UpdateBreakpointRemoveButton(); UpdateStatsLabel(); } @@ -358,7 +347,7 @@ namespace BizHawk.Client.EmuHawk.tools.Debugger return b; } - public enum BreakpointOperation + private enum BreakpointOperation { Add, Edit, Duplicate } diff --git a/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Designer.cs b/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Designer.cs index b7034cc73f..e0d3f9b754 100644 --- a/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Designer.cs +++ b/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Designer.cs @@ -42,7 +42,7 @@ this.RegistersGroupBox = new System.Windows.Forms.GroupBox(); this.RegisterPanel = new BizHawk.Client.EmuHawk.RegisterBoxControl(); this.BreakpointsGroupBox = new System.Windows.Forms.GroupBox(); - this.BreakPointControl1 = new BizHawk.Client.EmuHawk.tools.Debugger.BreakpointControl(); + this.BreakPointControl1 = new BizHawk.Client.EmuHawk.BreakpointControl(); this.DisassemblerBox = new System.Windows.Forms.GroupBox(); this.ToPCBtn = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); @@ -409,7 +409,7 @@ private System.Windows.Forms.GroupBox RegistersGroupBox; private RegisterBoxControl RegisterPanel; private System.Windows.Forms.GroupBox BreakpointsGroupBox; - private tools.Debugger.BreakpointControl BreakPointControl1; + private BreakpointControl BreakPointControl1; private System.Windows.Forms.GroupBox DisassemblerBox; private VirtualListView DisassemblerView; private System.Windows.Forms.ColumnHeader Address; diff --git a/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Disassembler.cs b/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Disassembler.cs index 9617500bd7..133341652f 100644 --- a/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Disassembler.cs +++ b/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.Disassembler.cs @@ -9,37 +9,31 @@ namespace BizHawk.Client.EmuHawk { public partial class GenericDebugger { - private readonly List DisassemblyLines = new List(); - int PCRegisterSize = 4; - uint currentDisassemblerAddress = 0; + private readonly List _disassemblyLines = new List(); + private int _pcRegisterSize = 4; + private uint _currentDisassemblerAddress; private class DisasmOp { - public DisasmOp(uint address, int s, string m) + public DisasmOp(uint address, int size, string mnemonic) { Address = address; - Size = s; - Mnemonic = m; + Size = size; + Mnemonic = mnemonic; } - public uint Address { get; private set; } - public int Size { get; private set; } - public string Mnemonic { get; private set; } + public uint Address { get; } + public int Size { get; } + public string Mnemonic { get; } } - private long BusMaxValue - { - get - { - return MemoryDomains.SystemBus.Size; - } - } + private long BusMaxValue => MemoryDomains.SystemBus.Size; - public void UpdatePC() + private void UpdatePC() { if (CanDisassemble) { - currentDisassemblerAddress = (uint)PCRegister.Value; + _currentDisassemblerAddress = (uint)PCRegister.Value; } } @@ -56,15 +50,15 @@ namespace BizHawk.Client.EmuHawk private void Disassemble() { - int line_count = DisassemblerView.NumberOfVisibleRows; + int lineCount = DisassemblerView.NumberOfVisibleRows; - DisassemblyLines.Clear(); - uint a = currentDisassemblerAddress; - for (int i = 0; i <= line_count; ++i) + _disassemblyLines.Clear(); + uint a = _currentDisassemblerAddress; + for (int i = 0; i <= lineCount; ++i) { int advance; string line = Disassembler.Disassemble(MemoryDomains.SystemBus, a, out advance); - DisassemblyLines.Add(new DisasmOp(a, advance, line)); + _disassemblyLines.Add(new DisasmOp(a, advance, line)); a += (uint)advance; if (a > BusMaxValue) { @@ -77,24 +71,24 @@ namespace BizHawk.Client.EmuHawk { text = ""; - if (index < DisassemblyLines.Count) + if (index < _disassemblyLines.Count) { if (column == 0) { - text = string.Format("{0:X" + PCRegisterSize + "}", DisassemblyLines[index].Address); + text = string.Format("{0:X" + _pcRegisterSize + "}", _disassemblyLines[index].Address); } else if (column == 1) { - text = DisassemblyLines[index].Mnemonic; + text = _disassemblyLines[index].Mnemonic; } } } private void DisassemblerView_QueryItemBkColor(int index, int column, ref Color color) { - if (DisassemblyLines.Any() && index < DisassemblyLines.Count) + if (_disassemblyLines.Any() && index < _disassemblyLines.Count) { - if (DisassemblyLines[index].Address == currentDisassemblerAddress) + if (_disassemblyLines[index].Address == _currentDisassemblerAddress) { color = Color.LightCyan; } @@ -103,15 +97,16 @@ namespace BizHawk.Client.EmuHawk private void DecrementCurrentAddress() { - uint newaddress = currentDisassemblerAddress; + uint newaddress = _currentDisassemblerAddress; while (true) { int bytestoadvance; Disassembler.Disassemble(MemoryDomains.SystemBus, newaddress, out bytestoadvance); - if (newaddress + bytestoadvance == currentDisassemblerAddress) + if (newaddress + bytestoadvance == _currentDisassemblerAddress) { break; } + newaddress--; if (newaddress < 0) @@ -121,22 +116,22 @@ namespace BizHawk.Client.EmuHawk } // Just in case - if (currentDisassemblerAddress - newaddress > 5) + if (_currentDisassemblerAddress - newaddress > 5) { - newaddress = currentDisassemblerAddress - 1; + newaddress = _currentDisassemblerAddress - 1; break; } } - currentDisassemblerAddress = newaddress; + _currentDisassemblerAddress = newaddress; } private void IncrementCurrentAddress() { - currentDisassemblerAddress += (uint)DisassemblyLines.First().Size; - if (currentDisassemblerAddress >= BusMaxValue) + _currentDisassemblerAddress += (uint)_disassemblyLines.First().Size; + if (_currentDisassemblerAddress >= BusMaxValue) { - currentDisassemblerAddress = (uint)(BusMaxValue - 1); + _currentDisassemblerAddress = (uint)(BusMaxValue - 1); } } @@ -188,12 +183,16 @@ namespace BizHawk.Client.EmuHawk var blob = new StringBuilder(); foreach (int index in indices) { - if (blob.Length != 0) blob.AppendLine(); + if (blob.Length != 0) + { + blob.AppendLine(); + } - blob.Append(string.Format("{0:X" + PCRegisterSize + "}", DisassemblyLines[index].Address)) + blob.Append(string.Format("{0:X" + _pcRegisterSize + "}", _disassemblyLines[index].Address)) .Append(" ") - .Append(DisassemblyLines[index].Mnemonic); + .Append(_disassemblyLines[index].Mnemonic); } + Clipboard.SetDataObject(blob.ToString()); } } @@ -201,7 +200,9 @@ namespace BizHawk.Client.EmuHawk private void OnPauseChanged(object sender, MainForm.PauseChangedEventArgs e) { if (e.Paused) + { FullUpdate(); + } } private void DisassemblerContextMenu_Opening(object sender, EventArgs e) @@ -215,7 +216,7 @@ namespace BizHawk.Client.EmuHawk if (indices.Count > 0) { - var line = DisassemblyLines[indices[0]]; + var line = _disassemblyLines[indices[0]]; BreakPointControl1.AddBreakpoint(line.Address, 0xFFFFFFFF, Emulation.Common.MemoryCallbackType.Execute); } } diff --git a/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.cs b/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.cs index 4c6f1ff97c..e15f973653 100644 --- a/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.cs +++ b/BizHawk.Client.EmuHawk/tools/Debugger/GenericDebugger.cs @@ -1,14 +1,9 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Emulation.Common; -using BizHawk.Emulation.Common.IEmulatorExtensions; using BizHawk.Client.Common; namespace BizHawk.Client.EmuHawk @@ -27,12 +22,11 @@ namespace BizHawk.Client.EmuHawk private void GenericDebugger_Load(object sender, EventArgs e) { - } private void EngageDebugger() { - DisassemblyLines.Clear(); + _disassemblyLines.Clear(); GlobalWin.MainForm.OnPauseChanged += OnPauseChanged; CancelSeekBtn.Enabled = false; if (CanDisassemble) @@ -74,7 +68,7 @@ namespace BizHawk.Client.EmuHawk }); } - PCRegisterSize = Debuggable.GetCpuFlagsAndRegisters()[Disassembler.PCRegisterName].BitSize / 4; + _pcRegisterSize = Debuggable.GetCpuFlagsAndRegisters()[Disassembler.PCRegisterName].BitSize / 4; SetDisassemblerItemCount(); UpdateDisassembler(); } @@ -187,7 +181,6 @@ namespace BizHawk.Client.EmuHawk private void DebugSubMenu_DropDownOpened(object sender, EventArgs e) { - } private void RunBtn_Click(object sender, EventArgs e) @@ -231,23 +224,24 @@ namespace BizHawk.Client.EmuHawk StepIntoMenuItem_Click(null, null); return true; } - else if (keyData == (Keys.F11 | Keys.Shift)) + + if (keyData == (Keys.F11 | Keys.Shift)) { StepOutMenuItem_Click(null, null); return true; } - else if (keyData == Keys.F10) + + if (keyData == Keys.F10) { StepOverMenuItem_Click(null, null); return true; } - else - { - return base.ProcessCmdKey(ref msg, keyData); - } + + return base.ProcessCmdKey(ref msg, keyData); } private Control _currentToolTipControl = null; + private void GenericDebugger_MouseMove(object sender, MouseEventArgs e) { var control = GetChildAtPoint(e.Location); diff --git a/BizHawk.Client.EmuHawk/tools/Debugger/RegisterBoxControl.cs b/BizHawk.Client.EmuHawk/tools/Debugger/RegisterBoxControl.cs index c6e1b57bc8..9f6d273e8f 100644 --- a/BizHawk.Client.EmuHawk/tools/Debugger/RegisterBoxControl.cs +++ b/BizHawk.Client.EmuHawk/tools/Debugger/RegisterBoxControl.cs @@ -1,10 +1,6 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; -using System.Data; using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Client.Common; @@ -30,7 +26,6 @@ namespace BizHawk.Client.EmuHawk private void RegisterBoxControl_Load(object sender, EventArgs e) { - } public void NewUpdate(ToolFormUpdateType type) { } @@ -63,7 +58,6 @@ namespace BizHawk.Client.EmuHawk if (_canSetCpuRegisters) { - Controls .OfType() .ToList() @@ -192,7 +186,6 @@ namespace BizHawk.Client.EmuHawk } catch (FormatException) { - } } }; @@ -230,10 +223,10 @@ namespace BizHawk.Client.EmuHawk { var c = new CheckBox { - Appearance = System.Windows.Forms.Appearance.Button, + Appearance = Appearance.Button, Name = flag.Key, Text = flag.Key.Replace("Flag", "").Trim(), // Hack - Checked = flag.Value.Value == 1 ? true : false, + Checked = flag.Value.Value == 1, Location = new Point(UIHelper.ScaleX(40), y), Dock = DockStyle.Left, Size = new Size(UIHelper.ScaleX(23), UIHelper.ScaleY(23)), diff --git a/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs b/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs index 12010313ce..02752e22b6 100644 --- a/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs +++ b/BizHawk.Client.EmuHawk/tools/HexEditor/HexEditor.cs @@ -1489,7 +1489,13 @@ namespace BizHawk.Client.EmuHawk } UpdateValues(); - } + } + + private bool _lastSearchWasText = false; + private void SearchTypeChanged(bool isText) + { + _lastSearchWasText = isText; + } private void FindMenuItem_Click(object sender, EventArgs e) { @@ -1499,7 +1505,9 @@ namespace BizHawk.Client.EmuHawk _hexFind = new HexFind { InitialLocation = PointToScreen(AddressesLabel.Location), - InitialValue = _findStr + InitialValue = _findStr, + SearchTypeChangedCallback = SearchTypeChanged, + InitialText = _lastSearchWasText }; _hexFind.Show(); diff --git a/BizHawk.Client.EmuHawk/tools/HexEditor/HexFind.cs b/BizHawk.Client.EmuHawk/tools/HexEditor/HexFind.cs index 5716b5f43e..8bfd208351 100644 --- a/BizHawk.Client.EmuHawk/tools/HexEditor/HexFind.cs +++ b/BizHawk.Client.EmuHawk/tools/HexEditor/HexFind.cs @@ -1,6 +1,5 @@ using System; using System.Drawing; -using System.Linq; using System.Text; using System.Windows.Forms; @@ -14,7 +13,12 @@ namespace BizHawk.Client.EmuHawk ChangeCasing(); } + // Hacky values to remember the Hex vs Text radio selection across searches + public Action SearchTypeChangedCallback { get; set; } + public bool InitialText { get; set; } + public Point InitialLocation { get; set; } + public string InitialValue { @@ -29,8 +33,14 @@ namespace BizHawk.Client.EmuHawk Location = InitialLocation; } + if (InitialText) + { + TextRadio.Select(); + } + FindBox.Focus(); FindBox.Select(); + } private string GetFindBoxChars() @@ -44,14 +54,13 @@ namespace BizHawk.Client.EmuHawk { return FindBox.Text; } - - + var bytes = GlobalWin.Tools.HexEditor.ConvertTextToBytes(FindBox.Text); var bytestring = new StringBuilder(); foreach (var b in bytes) { - bytestring.Append(string.Format("{0:X2}", b)); + bytestring.Append($"{b:X2}"); } return bytestring.ToString(); @@ -77,7 +86,6 @@ namespace BizHawk.Client.EmuHawk if (HexRadio.Checked) { - FindBox = new HexTextBox { CharacterCasing = CharacterCasing.Upper, @@ -103,11 +111,13 @@ namespace BizHawk.Client.EmuHawk private void HexRadio_CheckedChanged(object sender, EventArgs e) { ChangeCasing(); + SearchTypeChangedCallback?.Invoke(false); } private void TextRadio_CheckedChanged(object sender, EventArgs e) { ChangeCasing(); + SearchTypeChangedCallback?.Invoke(true); } private void FindBox_KeyDown(object sender, KeyEventArgs e) diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Client.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Client.cs index 411c139626..54f514cbf4 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Client.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Client.cs @@ -8,17 +8,16 @@ using BizHawk.Common; using BizHawk.Emulation.Common; using BizHawk.Client.Common; - namespace BizHawk.Client.EmuHawk { [Description("A library for manipulating the EmuHawk client UI")] public sealed class EmuHawkLuaLibrary : LuaLibraryBase { [RequiredService] - public IEmulator Emulator { get; set; } + private IEmulator Emulator { get; set; } [RequiredService] - public IVideoProvider VideoProvider { get; set; } + private IVideoProvider VideoProvider { get; set; } private readonly Dictionary _filterMappings = new Dictionary { @@ -35,30 +34,22 @@ namespace BizHawk.Client.EmuHawk public EmuHawkLuaLibrary(Lua lua, Action logOutputCallback) : base(lua, logOutputCallback) { } - public override string Name { get { return "client"; } } + public override string Name => "client"; - [LuaMethodAttributes( - "exit", - "Closes the emulator" - )] + [LuaMethodAttributes("exit", "Closes the emulator")] public void CloseEmulator() { GlobalWin.MainForm.CloseEmulator(); } - [LuaMethodAttributes( - "exitCode", - "Closes the emulator and returns the provided code" - )] + [LuaMethodAttributes("exitCode", "Closes the emulator and returns the provided code")] public void CloseEmulatorWithCode(int exitCode) { GlobalWin.MainForm.CloseEmulator(exitCode); } [LuaMethodAttributes( - "borderheight", - "Gets the current height in pixels of the letter/pillarbox area (top side only) around the emu display surface, excluding the gameExtraPadding you've set. This function (the whole lot of them) should be renamed or refactored since the padding areas have got more complex." - )] + "borderheight", "Gets the current height in pixels of the letter/pillarbox area (top side only) around the emu display surface, excluding the gameExtraPadding you've set. This function (the whole lot of them) should be renamed or refactored since the padding areas have got more complex.")] public static int BorderHeight() { var point = new System.Drawing.Point(0, 0); @@ -66,9 +57,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "borderwidth", - "Gets the current width in pixels of the letter/pillarbox area (left side only) around the emu display surface, excluding the gameExtraPadding you've set. This function (the whole lot of them) should be renamed or refactored since the padding areas have got more complex." - )] + "borderwidth", "Gets the current width in pixels of the letter/pillarbox area (left side only) around the emu display surface, excluding the gameExtraPadding you've set. This function (the whole lot of them) should be renamed or refactored since the padding areas have got more complex.")] public static int BorderWidth() { var point = new System.Drawing.Point(0, 0); @@ -76,57 +65,38 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "bufferheight", - "Gets the visible height of the emu display surface (the core video output). This excludes the gameExtraPadding you've set." - )] + "bufferheight", "Gets the visible height of the emu display surface (the core video output). This excludes the gameExtraPadding you've set.")] public int BufferHeight() { return VideoProvider.BufferHeight; - //memento of original behaviour from scepheo's commit -- why? - //var point = new System.Drawing.Point(0, height); - //return GlobalWin.DisplayManager.TransformPoint(point).Y - BorderHeight(); } [LuaMethodAttributes( - "bufferwidth", - "Gets the visible width of the emu display surface (the core video output). This excludes the gameExtraPadding you've set." - )] + "bufferwidth", "Gets the visible width of the emu display surface (the core video output). This excludes the gameExtraPadding you've set.")] public int BufferWidth() { return VideoProvider.BufferWidth; } - [LuaMethodAttributes( - "clearautohold", - "Clears all autohold keys" - )] + [LuaMethodAttributes("clearautohold", "Clears all autohold keys")] public void ClearAutohold() { GlobalWin.MainForm.ClearHolds(); } - [LuaMethodAttributes( - "closerom", - "Closes the loaded Rom" - )] + [LuaMethodAttributes("closerom", "Closes the loaded Rom")] public static void CloseRom() { GlobalWin.MainForm.CloseRom(); } - [LuaMethodAttributes( - "enablerewind", - "Sets whether or not the rewind feature is enabled" - )] + [LuaMethodAttributes("enablerewind", "Sets whether or not the rewind feature is enabled")] public void EnableRewind(bool enabled) { GlobalWin.MainForm.EnableRewind(enabled); } - [LuaMethodAttributes( - "frameskip", - "Sets the frame skip value of the client UI" - )] + [LuaMethodAttributes("frameskip", "Sets the frame skip value of the client UI")] public void FrameSkip(int numFrames) { if (numFrames > 0) @@ -140,186 +110,125 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "gettargetscanlineintensity", - "Gets the current scanline intensity setting, used for the scanline display filter" - )] + [LuaMethodAttributes("gettargetscanlineintensity", "Gets the current scanline intensity setting, used for the scanline display filter")] public static int GetTargetScanlineIntensity() { return Global.Config.TargetScanlineFilterIntensity; } - [LuaMethodAttributes( - "getwindowsize", - "Gets the main window's size Possible values are 1, 2, 3, 4, 5, and 10" - )] + [LuaMethodAttributes("getwindowsize", "Gets the main window's size Possible values are 1, 2, 3, 4, 5, and 10")] public int GetWindowSize() { return Global.Config.TargetZoomFactors[Emulator.SystemId]; } - [LuaMethodAttributes( - "SetGameExtraPadding", - "Sets the extra padding added to the 'emu' surface so that you can draw HUD elements in predictable placements" - )] + [LuaMethodAttributes("SetGameExtraPadding", "Sets the extra padding added to the 'emu' surface so that you can draw HUD elements in predictable placements")] public static void SetGameExtraPadding(int left, int top, int right, int bottom) { GlobalWin.DisplayManager.GameExtraPadding = new System.Windows.Forms.Padding(left, top, right, bottom); GlobalWin.MainForm.FrameBufferResized(); } - [LuaMethodAttributes( - "SetSoundOn", - "Sets the state of the Sound On toggle" - )] + [LuaMethodAttributes("SetSoundOn", "Sets the state of the Sound On toggle")] public static void SetSoundOn(bool enable) { Global.Config.SoundEnabled = enable; } - [LuaMethodAttributes( - "GetSoundOn", - "Gets the state of the Sound On toggle" - )] + [LuaMethodAttributes("GetSoundOn", "Gets the state of the Sound On toggle")] public static bool GetSoundOn() { return Global.Config.SoundEnabled; } - [LuaMethodAttributes( - "SetClientExtraPadding", - "Sets the extra padding added to the 'native' surface so that you can draw HUD elements in predictable placements" - )] + [LuaMethodAttributes("SetClientExtraPadding", "Sets the extra padding added to the 'native' surface so that you can draw HUD elements in predictable placements")] public static void SetClientExtraPadding(int left, int top, int right, int bottom) { GlobalWin.DisplayManager.ClientExtraPadding = new System.Windows.Forms.Padding(left, top, right, bottom); GlobalWin.MainForm.FrameBufferResized(); } - [LuaMethodAttributes( - "ispaused", - "Returns true if emulator is paused, otherwise, false" - )] + [LuaMethodAttributes("ispaused", "Returns true if emulator is paused, otherwise, false")] public static bool IsPaused() { return GlobalWin.MainForm.EmulatorPaused; } - [LuaMethodAttributes( - "opencheats", - "opens the Cheats dialog" - )] + [LuaMethodAttributes("opencheats", "opens the Cheats dialog")] public static void OpenCheats() { GlobalWin.Tools.Load(); } - [LuaMethodAttributes( - "openhexeditor", - "opens the Hex Editor dialog" - )] + [LuaMethodAttributes("openhexeditor", "opens the Hex Editor dialog")] public static void OpenHexEditor() { GlobalWin.Tools.Load(); } - [LuaMethodAttributes( - "openramwatch", - "opens the RAM Watch dialog" - )] + [LuaMethodAttributes("openramwatch", "opens the RAM Watch dialog")] public static void OpenRamWatch() { GlobalWin.Tools.LoadRamWatch(loadDialog: true); } - [LuaMethodAttributes( - "openramsearch", - "opens the RAM Search dialog" - )] + [LuaMethodAttributes("openramsearch", "opens the RAM Search dialog")] public static void OpenRamSearch() { GlobalWin.Tools.Load(); } - [LuaMethodAttributes( - "openrom", - "opens the Open ROM dialog" - )] + [LuaMethodAttributes("openrom", "opens the Open ROM dialog")] public static void OpenRom(string path) { - GlobalWin.MainForm.LoadRom(path, new MainForm.LoadRomArgs() { OpenAdvanced = new OpenAdvanced_OpenRom() }); + GlobalWin.MainForm.LoadRom(path, new MainForm.LoadRomArgs { OpenAdvanced = new OpenAdvanced_OpenRom() }); } - [LuaMethodAttributes( - "opentasstudio", - "opens the TAStudio dialog" - )] + [LuaMethodAttributes("opentasstudio", "opens the TAStudio dialog")] public static void OpenTasStudio() { GlobalWin.Tools.Load(); } - [LuaMethodAttributes( - "opentoolbox", - "opens the Toolbox Dialog" - )] + [LuaMethodAttributes("opentoolbox", "opens the Toolbox Dialog")] public static void OpenToolBox() { GlobalWin.Tools.Load(); } - [LuaMethodAttributes( - "opentracelogger", - "opens the tracelogger if it is available for the given core" - )] + [LuaMethodAttributes("opentracelogger", "opens the tracelogger if it is available for the given core")] public static void OpenTraceLogger() { GlobalWin.Tools.Load(); } - [LuaMethodAttributes( - "pause", - "Pauses the emulator" - )] + [LuaMethodAttributes("pause", "Pauses the emulator")] public static void Pause() { GlobalWin.MainForm.PauseEmulator(); } - [LuaMethodAttributes( - "pause_av", - "If currently capturing Audio/Video, this will suspend the record. Frames will not be captured into the AV until client.unpause_av() is called" - )] + [LuaMethodAttributes("pause_av", "If currently capturing Audio/Video, this will suspend the record. Frames will not be captured into the AV until client.unpause_av() is called")] public static void PauseAv() { - GlobalWin.MainForm.PauseAVI = true; + GlobalWin.MainForm.PauseAvi = true; } - [LuaMethodAttributes( - "reboot_core", - "Reboots the currently loaded core" - )] + [LuaMethodAttributes("reboot_core", "Reboots the currently loaded core")] public static void RebootCore() { - //pretty hacky.. we dont want a lua script to be able to restart itself by rebooting the core - ((LuaConsole)GlobalWin.Tools.Get()).IsRebootingCore = true; + ((LuaConsole)GlobalWin.Tools.Get()).LuaImp.IsRebootingCore = true; GlobalWin.MainForm.RebootCore(); - ((LuaConsole)GlobalWin.Tools.Get()).IsRebootingCore = false; + ((LuaConsole)GlobalWin.Tools.Get()).LuaImp.IsRebootingCore = false; } - [LuaMethodAttributes( - "screenheight", - "Gets the current height in pixels of the emulator's drawing area" - )] + [LuaMethodAttributes("screenheight", "Gets the current height in pixels of the emulator's drawing area")] public static int ScreenHeight() { return GlobalWin.MainForm.PresentationPanel.NativeSize.Height; } - [LuaMethodAttributes( - "screenshot", - "if a parameter is passed it will function as the Screenshot As menu item of EmuHawk, else it will function as the Screenshot menu item" - )] + [LuaMethodAttributes("screenshot", "if a parameter is passed it will function as the Screenshot As menu item of EmuHawk, else it will function as the Screenshot menu item")] public static void Screenshot(string path = null) { if (path == null) @@ -332,46 +241,31 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "screenshottoclipboard", - "Performs the same function as EmuHawk's Screenshot To Clipboard menu item" - )] + [LuaMethodAttributes("screenshottoclipboard", "Performs the same function as EmuHawk's Screenshot To Clipboard menu item")] public static void ScreenshotToClipboard() { GlobalWin.MainForm.TakeScreenshotToClipboard(); } - [LuaMethodAttributes( - "settargetscanlineintensity", - "Sets the current scanline intensity setting, used for the scanline display filter" - )] + [LuaMethodAttributes("settargetscanlineintensity", "Sets the current scanline intensity setting, used for the scanline display filter")] public static void SetTargetScanlineIntensity(int val) { Global.Config.TargetScanlineFilterIntensity = val; } - [LuaMethodAttributes( - "setscreenshotosd", - "Sets the screenshot Capture OSD property of the client" - )] + [LuaMethodAttributes("setscreenshotosd", "Sets the screenshot Capture OSD property of the client")] public static void SetScreenshotOSD(bool value) { Global.Config.Screenshot_CaptureOSD = value; } - [LuaMethodAttributes( - "screenwidth", - "Gets the current width in pixels of the emulator's drawing area" - )] + [LuaMethodAttributes("screenwidth", "Gets the current width in pixels of the emulator's drawing area")] public static int ScreenWidth() { return GlobalWin.MainForm.PresentationPanel.NativeSize.Width; } - [LuaMethodAttributes( - "setwindowsize", - "Sets the main window's size to the give value. Accepted values are 1, 2, 3, 4, 5, and 10" - )] + [LuaMethodAttributes("setwindowsize", "Sets the main window's size to the give value. Accepted values are 1, 2, 3, 4, 5, and 10")] public void SetWindowSize(int size) { if (size == 1 || size == 2 || size == 3 || size == 4 || size == 5 || size == 10) @@ -386,10 +280,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "speedmode", - "Sets the speed of the emulator (in terms of percent)" - )] + [LuaMethodAttributes("speedmode", "Sets the speed of the emulator (in terms of percent)")] public void SpeedMode(int percent) { if (percent > 0 && percent < 6400) @@ -402,75 +293,51 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "togglepause", - "Toggles the current pause state" - )] + [LuaMethodAttributes("togglepause", "Toggles the current pause state")] public static void TogglePause() { GlobalWin.MainForm.TogglePause(); } - [LuaMethodAttributes( - "transformPointX", - "Transforms an x-coordinate in emulator space to an x-coordinate in client space" - )] + [LuaMethodAttributes("transformPointX", "Transforms an x-coordinate in emulator space to an x-coordinate in client space")] public static int TransformPointX(int x) { var point = new System.Drawing.Point(x, 0); return GlobalWin.DisplayManager.TransformPoint(point).X; } - [LuaMethodAttributes( - "transformPointY", - "Transforms an y-coordinate in emulator space to an y-coordinate in client space" - )] + [LuaMethodAttributes("transformPointY", "Transforms an y-coordinate in emulator space to an y-coordinate in client space")] public static int TransformPointY(int y) { var point = new System.Drawing.Point(0, y); return GlobalWin.DisplayManager.TransformPoint(point).Y; } - [LuaMethodAttributes( - "unpause", - "Unpauses the emulator" - )] + [LuaMethodAttributes("unpause", "Unpauses the emulator")] public static void Unpause() { GlobalWin.MainForm.UnpauseEmulator(); } - [LuaMethodAttributes( - "unpause_av", - "If currently capturing Audio/Video this resumes capturing" - )] + [LuaMethodAttributes("unpause_av", "If currently capturing Audio/Video this resumes capturing")] public static void UnpauseAv() { - GlobalWin.MainForm.PauseAVI = false; + GlobalWin.MainForm.PauseAvi = false; } - [LuaMethodAttributes( - "xpos", - "Returns the x value of the screen position where the client currently sits" - )] + [LuaMethodAttributes("xpos", "Returns the x value of the screen position where the client currently sits")] public static int Xpos() { return GlobalWin.MainForm.DesktopLocation.X; } - [LuaMethodAttributes( - "ypos", - "Returns the y value of the screen position where the client currently sits" - )] + [LuaMethodAttributes("ypos", "Returns the y value of the screen position where the client currently sits")] public static int Ypos() { return GlobalWin.MainForm.DesktopLocation.Y; } - [LuaMethodAttributes( - "getavailabletools", - "Returns a list of the tools currently open" - )] + [LuaMethodAttributes("getavailabletools", "Returns a list of the tools currently open")] public LuaTable GetAvailableTools() { var t = Lua.NewTable(); @@ -484,9 +351,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "gettool", - "Returns an object that represents a tool of the given name (not case sensitive). If the tool is not open, it will be loaded if available. Use gettools to get a list of names" - )] + "gettool", "Returns an object that represents a tool of the given name (not case sensitive). If the tool is not open, it will be loaded if available. Use gettools to get a list of names")] public LuaTable GetTool(string name) { var toolType = ReflectionUtil.GetTypeByName(name) @@ -509,9 +374,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "createinstance", - "returns a default instance of the given type of object if it exists (not case sensitive). Note: This will only work on objects which have a parameterless constructor. If no suitable type is found, or the type does not have a parameterless constructor, then nil is returned" - )] + "createinstance", "returns a default instance of the given type of object if it exists (not case sensitive). Note: This will only work on objects which have a parameterless constructor. If no suitable type is found, or the type does not have a parameterless constructor, then nil is returned")] public LuaTable CreateInstance(string name) { var possibleTypes = ReflectionUtil.GetTypeByName(name); @@ -525,19 +388,13 @@ namespace BizHawk.Client.EmuHawk return null; } - [LuaMethodAttributes( - "displaymessages", - "sets whether or not on screen messages will display" - )] + [LuaMethodAttributes("displaymessages", "sets whether or not on screen messages will display")] public void DisplayMessages(bool value) { Global.Config.DisplayMessages = value; } - [LuaMethodAttributes( - "saveram", - "flushes save ram to disk" - )] + [LuaMethodAttributes("saveram", "flushes save ram to disk")] public void SaveRam() { GlobalWin.MainForm.FlushSaveRAM(); diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Console.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Console.cs index a513831505..7320d1d6c4 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Console.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Console.cs @@ -16,21 +16,18 @@ namespace BizHawk.Client.EmuHawk public ConsoleLuaLibrary(Lua lua, Action logOutputCallback) : base(lua, logOutputCallback) { } - public override string Name { get { return "console"; } } + public override string Name => "console"; - [LuaMethodAttributes( - "clear", - "clears the output box of the Lua Console window" - )] + [LuaMethodAttributes("clear", "clears the output box of the Lua Console window")] public static void Clear() { - GlobalWin.Tools.LuaConsole.ClearOutputWindow(); + if (GlobalWin.Tools.Has()) + { + GlobalWin.Tools.LuaConsole.ClearOutputWindow(); + } } - [LuaMethodAttributes( - "getluafunctionslist", - "returns a list of implemented functions" - )] + [LuaMethodAttributes("getluafunctionslist", "returns a list of implemented functions")] public static string GetLuaFunctionsList() { var list = new StringBuilder(); @@ -42,34 +39,34 @@ namespace BizHawk.Client.EmuHawk return list.ToString(); } - [LuaMethodAttributes( - "log", - "Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable" - )] + [LuaMethodAttributes("log", "Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable")] public static void Log(params object[] outputs) { - LogWithSeparator("\t", "\n", outputs); + if (GlobalWin.Tools.Has()) + { + LogWithSeparator("\t", "\n", outputs); + } } //// Single param version is used by logOutputCallback of some libraries. public static void LogOutput(object output) { - Log(output); + if (GlobalWin.Tools.Has()) + { + Log(output); + } } - [LuaMethodAttributes( - "writeline", - "Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable" - )] + [LuaMethodAttributes("writeline", "Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable")] public static void WriteLine(params object[] outputs) { - LogWithSeparator("\n", "\n", outputs); + if (GlobalWin.Tools.Has()) + { + LogWithSeparator("\n", "\n", outputs); + } } - [LuaMethodAttributes( - "write", - "Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable" - )] + [LuaMethodAttributes("write", "Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable")] public static void Write(params object[] outputs) { LogWithSeparator("", "", outputs); @@ -78,11 +75,17 @@ namespace BizHawk.Client.EmuHawk // Outputs the given object to the output box on the Lua Console dialog. Note: Can accept a LuaTable private static void LogWithSeparator(string separator, string terminator, params object[] outputs) { + if (!GlobalWin.Tools.Has()) + { + return; + } + if (outputs == null) { GlobalWin.Tools.LuaConsole.WriteToOutputWindow("(no return)" + terminator); return; } + for (var outIndex = 0; outIndex < outputs.Length; outIndex++) { var output = outputs[outIndex]; @@ -135,6 +138,7 @@ namespace BizHawk.Client.EmuHawk } } } + GlobalWin.Tools.LuaConsole.WriteToOutputWindow(terminator); } } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Forms.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Forms.cs index 609a9722ca..1ad7cdae9e 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Forms.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Forms.cs @@ -20,7 +20,7 @@ namespace BizHawk.Client.EmuHawk : base(lua, logOutputCallback) { } // TODO: replace references to ConsoleLuaLibrary.Log with a callback that is passed in - public override string Name { get { return "forms"; } } + public override string Name => "forms"; #region Forms Library Helpers @@ -61,10 +61,7 @@ namespace BizHawk.Client.EmuHawk #endregion - [LuaMethodAttributes( - "addclick", - "adds the given lua function as a click event to the given control" - )] + [LuaMethodAttributes("addclick", "adds the given lua function as a click event to the given control")] public void AddClick(int handle, LuaFunction clickEvent) { var ptr = new IntPtr(handle); @@ -81,9 +78,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "button", - "Creates a button control on the given form. The caption property will be the text value on the button. clickEvent is the name of a Lua function that will be invoked when the button is clicked. x, and y are the optional location parameters for the position of the button within the given form. The function returns the handle of the created button. Width and Height are optional, if not specified they will be a default size" - )] + "button", "Creates a button control on the given form. The caption property will be the text value on the button. clickEvent is the name of a Lua function that will be invoked when the button is clicked. x, and y are the optional location parameters for the position of the button within the given form. The function returns the handle of the created button. Width and Height are optional, if not specified they will be a default size")] public int Button( int formHandle, string caption, @@ -118,9 +113,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "checkbox", - "Creates a checkbox control on the given form. The caption property will be the text of the checkbox. x and y are the optional location parameters for the position of the checkbox within the form" - )] + "checkbox", "Creates a checkbox control on the given form. The caption property will be the text of the checkbox. x and y are the optional location parameters for the position of the checkbox within the form")] public int Checkbox(int formHandle, string caption, int? x = null, int? y = null) { var form = GetForm(formHandle); @@ -141,10 +134,7 @@ namespace BizHawk.Client.EmuHawk return (int)checkbox.Handle; } - [LuaMethodAttributes( - "clearclicks", - "Removes all click events from the given widget at the specified handle" - )] + [LuaMethodAttributes("clearclicks", "Removes all click events from the given widget at the specified handle")] public void ClearClicks(int handle) { var ptr = new IntPtr(handle); @@ -164,10 +154,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "destroy", - "Closes and removes a Lua created form with the specified handle. If a dialog was found and removed true is returned, else false" - )] + [LuaMethodAttributes("destroy", "Closes and removes a Lua created form with the specified handle. If a dialog was found and removed true is returned, else false")] public bool Destroy(int handle) { var ptr = new IntPtr(handle); @@ -184,10 +171,7 @@ namespace BizHawk.Client.EmuHawk return false; } - [LuaMethodAttributes( - "destroyall", - "Closes and removes all Lua created dialogs" - )] + [LuaMethodAttributes("destroyall", "Closes and removes all Lua created dialogs")] public void DestroyAll() { for (var i = _luaForms.Count - 1; i >= 0; i--) @@ -197,9 +181,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "dropdown", - "Creates a dropdown (with a ComboBoxStyle of DropDownList) control on the given form. Dropdown items are passed via a lua table. Only the values will be pulled for the dropdown items, the keys are irrelevant. Items will be sorted alphabetically. x and y are the optional location parameters, and width and height are the optional size parameters." - )] + "dropdown", "Creates a dropdown (with a ComboBoxStyle of DropDownList) control on the given form. Dropdown items are passed via a lua table. Only the values will be pulled for the dropdown items, the keys are irrelevant. Items will be sorted alphabetically. x and y are the optional location parameters, and width and height are the optional size parameters.")] public int Dropdown( int formHandle, LuaTable items, @@ -233,10 +215,7 @@ namespace BizHawk.Client.EmuHawk return (int)dropdown.Handle; } - [LuaMethodAttributes( - "getproperty", - "returns a string representation of the value of a property of the widget at the given handle" - )] + [LuaMethodAttributes("getproperty", "returns a string representation of the value of a property of the widget at the given handle")] public string GetProperty(int handle, string property) { try @@ -266,10 +245,7 @@ namespace BizHawk.Client.EmuHawk return ""; } - [LuaMethodAttributes( - "gettext", - "Returns the text property of a given form or control" - )] + [LuaMethodAttributes("gettext", "Returns the text property of a given form or control")] public string GetText(int handle) { try @@ -304,10 +280,7 @@ namespace BizHawk.Client.EmuHawk return ""; } - [LuaMethodAttributes( - "ischecked", - "Returns the given checkbox's checked property" - )] + [LuaMethodAttributes("ischecked", "Returns the given checkbox's checked property")] public bool IsChecked(int handle) { var ptr = new IntPtr(handle); @@ -336,9 +309,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "label", - "Creates a label control on the given form. The caption property is the text of the label. x, and y are the optional location parameters for the position of the label within the given form. The function returns the handle of the created label. Width and Height are optional, if not specified they will be a default size." - )] + "label", "Creates a label control on the given form. The caption property is the text of the label. x, and y are the optional location parameters for the position of the label within the given form. The function returns the handle of the created label. Width and Height are optional, if not specified they will be a default size.")] public int Label( int formHandle, string caption, @@ -377,9 +348,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "newform", - "creates a new default dialog, if both width and height are specified it will create a dialog of the specified size. If title is specified it will be the caption of the dialog, else the dialog caption will be 'Lua Dialog'. The function will return an int representing the handle of the dialog created." - )] + "newform", "creates a new default dialog, if both width and height are specified it will create a dialog of the specified size. If title is specified it will be the caption of the dialog, else the dialog caption will be 'Lua Dialog'. The function will return an int representing the handle of the dialog created.")] public int NewForm(int? width = null, int? height = null, string title = null, LuaFunction onClose = null) { var form = new LuaWinform(CurrentThread); @@ -414,9 +383,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "openfile", - "Creates a standard openfile dialog with optional parameters for the filename, directory, and filter. The return value is the directory that the user picked. If they chose to cancel, it will return an empty string" - )] + "openfile", "Creates a standard openfile dialog with optional parameters for the filename, directory, and filter. The return value is the directory that the user picked. If they chose to cancel, it will return an empty string")] public string OpenFile(string fileName = null, string initialDirectory = null, string filter = "All files (*.*)|*.*") { // filterext format ex: "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*" @@ -445,24 +412,25 @@ namespace BizHawk.Client.EmuHawk return ""; } - [LuaMethodAttributes( - "setdropdownitems", - "Sets the items for a given dropdown box" - )] - public void SetDropdownItems( - int handle, - LuaTable items) + [LuaMethodAttributes("setdropdownitems", "Sets the items for a given dropdown box")] + public void SetDropdownItems(int handle, LuaTable items) { - try { + try + { var ptr = new IntPtr(handle); - foreach (var form in _luaForms) { - if (form.Handle == ptr) { + foreach (var form in _luaForms) + { + if (form.Handle == ptr) + { return; } - foreach (Control control in form.Controls) { - if (control.Handle == ptr) { - if (control is LuaDropDown) { + foreach (Control control in form.Controls) + { + if (control.Handle == ptr) + { + if (control is LuaDropDown) + { var dropdownItems = items.Values.Cast().ToList(); dropdownItems.Sort(); (control as LuaDropDown).SetItems(dropdownItems); @@ -472,15 +440,14 @@ namespace BizHawk.Client.EmuHawk } } } - } catch (Exception ex) { - ConsoleLuaLibrary.Log(ex.Message); + } + catch (Exception ex) + { + Log(ex.Message); } } - [LuaMethodAttributes( - "setlocation", - "Sets the location of a control or form by passing in the handle of the created object" - )] + [LuaMethodAttributes("setlocation", "Sets the location of a control or form by passing in the handle of the created object")] public void SetLocation(int handle, int x, int y) { var ptr = new IntPtr(handle); @@ -503,10 +470,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "setproperty", - "Attempts to set the given property of the widget with the given value. Note: not all properties will be able to be represented for the control to accept" - )] + [LuaMethodAttributes("setproperty", "Attempts to set the given property of the widget with the given value. Note: not all properties will be able to be represented for the control to accept")] public void SetProperty(int handle, string property, object value) { var ptr = new IntPtr(handle); @@ -519,16 +483,25 @@ namespace BizHawk.Client.EmuHawk { value = Enum.Parse(form.GetType().GetProperty(property).PropertyType, value.ToString(), true); } + if (pt == typeof(Color)) { - //relying on exceptions for error handling here + // relying on exceptions for error handling here var sval = (string)value; - if (sval[0] != '#') throw new Exception("Invalid #aarrggbb color"); - if (sval.Length != 9) throw new Exception("Invalid #aarrggbb color"); + if (sval[0] != '#') + { + throw new Exception("Invalid #aarrggbb color"); + } + + if (sval.Length != 9) + { + throw new Exception("Invalid #aarrggbb color"); + } + value = Color.FromArgb(int.Parse(sval.Substring(1),System.Globalization.NumberStyles.HexNumber)); } - form - .GetType() + + form.GetType() .GetProperty(property) .SetValue(form, Convert.ChangeType(value, form.GetType().GetProperty(property).PropertyType), null); } @@ -542,8 +515,8 @@ namespace BizHawk.Client.EmuHawk { value = Enum.Parse(control.GetType().GetProperty(property).PropertyType, value.ToString(), true); } - control - .GetType() + + control.GetType() .GetProperty(property) .SetValue(control, Convert.ChangeType(value, control.GetType().GetProperty(property).PropertyType), null); } @@ -552,19 +525,13 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "createcolor", - "Creates a color object useful with setproperty" - )] + [LuaMethodAttributes("createcolor", "Creates a color object useful with setproperty")] public Color CreateColor(int r, int g, int b, int a) { return Color.FromArgb(a, r, g, b); } - [LuaMethodAttributes( - "setsize", - "TODO" - )] + [LuaMethodAttributes("setsize", "TODO")] public void SetSize(int handle, int width, int height) { var ptr = new IntPtr(handle); @@ -587,10 +554,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "settext", - "Sets the text property of a control or form by passing in the handle of the created object" - )] + [LuaMethodAttributes("settext", "Sets the text property of a control or form by passing in the handle of the created object")] public void Settext(int handle, string caption) { var ptr = new IntPtr(handle); @@ -614,9 +578,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "textbox", - "Creates a textbox control on the given form. The caption property will be the initial value of the textbox (default is empty). Width and Height are option, if not specified they will be a default size of 100, 20. Type is an optional property to restrict the textbox input. The available options are HEX, SIGNED, and UNSIGNED. Passing it null or any other value will set it to no restriction. x, and y are the optional location parameters for the position of the textbox within the given form. The function returns the handle of the created textbox. If true, the multiline will enable the standard winform multi-line property. If true, the fixedWidth options will create a fixed width font. Scrollbars is an optional property to specify which scrollbars to display. The available options are Vertical, Horizontal, Both, and None. Scrollbars are only shown on a multiline textbox" - )] + "textbox", "Creates a textbox control on the given form. The caption property will be the initial value of the textbox (default is empty). Width and Height are option, if not specified they will be a default size of 100, 20. Type is an optional property to restrict the textbox input. The available options are HEX, SIGNED, and UNSIGNED. Passing it null or any other value will set it to no restriction. x, and y are the optional location parameters for the position of the textbox within the given form. The function returns the handle of the created textbox. If true, the multiline will enable the standard winform multi-line property. If true, the fixedWidth options will create a fixed width font. Scrollbars is an optional property to specify which scrollbars to display. The available options are Vertical, Horizontal, Both, and None. Scrollbars are only shown on a multiline textbox")] public int Textbox( int formHandle, string caption = null, @@ -662,6 +624,7 @@ namespace BizHawk.Client.EmuHawk break; } } + SetText(textbox, caption); if (x.HasValue && y.HasValue) diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Gui.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Gui.cs index 96d6429d05..9956127cfb 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Gui.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Gui.cs @@ -13,7 +13,7 @@ namespace BizHawk.Client.EmuHawk public sealed class GuiLuaLibrary : LuaLibraryBase { [RequiredService] - public IEmulator Emulator { get; set; } + private IEmulator Emulator { get; set; } public GuiLuaLibrary(Lua lua) : base(lua) { } @@ -21,12 +21,12 @@ namespace BizHawk.Client.EmuHawk public GuiLuaLibrary(Lua lua, Action logOutputCallback) : base(lua, logOutputCallback) { } - private Color DefaultForeground = Color.White; - private Color? DefaultBackground = null; - private Color? DefaultTextBackground = Color.FromArgb(128, 0, 0, 0); - private int DefaultPixelFont = 1; // gens + private Color _defaultForeground = Color.White; + private Color? _defaultBackground; + private Color? _defaultTextBackground = Color.FromArgb(128, 0, 0, 0); + private int _defaultPixelFont = 1; // gens - public override string Name { get { return "gui"; } } + public override string Name => "gui"; #region Gui API @@ -43,24 +43,16 @@ namespace BizHawk.Client.EmuHawk } } - public bool SurfaceIsNull - { - get - { - return _luaSurface == null; - } - } + public bool SurfaceIsNull => _luaSurface == null; [LuaMethodAttributes( - "DrawNew", - "Changes drawing target to the specified lua surface name. This may clobber any previous drawing to this surface (pass false if you don't want it to)" - )] - public void DrawNew(string name, bool? clear=true) + "DrawNew", "Changes drawing target to the specified lua surface name. This may clobber any previous drawing to this surface (pass false if you don't want it to)")] + public void DrawNew(string name, bool? clear = true) { try { DrawFinish(); - _luaSurface = GlobalWin.DisplayManager.LockLuaSurface(name,clear??true); + _luaSurface = GlobalWin.DisplayManager.LockLuaSurface(name, clear ?? true); } catch (InvalidOperationException ex) { @@ -68,25 +60,23 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "DrawFinish", - "Finishes drawing to the current lua surface and causes it to get displayed." - )] + [LuaMethodAttributes("DrawFinish", "Finishes drawing to the current lua surface and causes it to get displayed.")] public void DrawFinish() { - if(_luaSurface != null) + if (_luaSurface != null) + { GlobalWin.DisplayManager.UnlockLuaSurface(_luaSurface); + } + _luaSurface = null; } - public bool HasLuaSurface - { - get { return _luaSurface != null; } - } + public bool HasLuaSurface => _luaSurface != null; #endregion #region Helpers + private readonly Dictionary _imageCache = new Dictionary(); private readonly Dictionary _solidBrushes = new Dictionary(); private readonly Dictionary _pens = new Dictionary(); @@ -122,7 +112,7 @@ namespace BizHawk.Client.EmuHawk { var g = _luaSurface == null ? Graphics.FromImage(_nullGraphicsBitmap) : _luaSurface.GetGraphics(); - //we don't like CoreComm, right? Someone should find a different way to do this then. + // we don't like CoreComm, right? Someone should find a different way to do this then. var tx = Emulator.CoreComm.ScreenLogicalOffsetX; var ty = Emulator.CoreComm.ScreenLogicalOffsetY; if (tx != 0 || ty != 0) @@ -137,89 +127,64 @@ namespace BizHawk.Client.EmuHawk #endregion - [LuaMethodAttributes( - "addmessage", - "Adds a message to the OSD's message area" - )] + [LuaMethodAttributes("addmessage", "Adds a message to the OSD's message area")] public void AddMessage(string message) { GlobalWin.OSD.AddMessage(message); } - [LuaMethodAttributes( - "clearGraphics", - "clears all lua drawn graphics from the screen" - )] + [LuaMethodAttributes("clearGraphics", "clears all lua drawn graphics from the screen")] public void ClearGraphics() { _luaSurface.Clear(); DrawFinish(); } - [LuaMethodAttributes( - "cleartext", - "clears all text created by gui.text()" - )] + [LuaMethodAttributes("cleartext", "clears all text created by gui.text()")] public static void ClearText() { GlobalWin.OSD.ClearGUIText(); } - [LuaMethodAttributes( - "defaultForeground", - "Sets the default foreground color to use in drawing methods, white by default" - )] + [LuaMethodAttributes("defaultForeground", "Sets the default foreground color to use in drawing methods, white by default")] public void SetDefaultForegroundColor(Color color) { - DefaultForeground = color; + _defaultForeground = color; } - [LuaMethodAttributes( - "defaultBackground", - "Sets the default background color to use in drawing methods, transparent by default" - )] + [LuaMethodAttributes("defaultBackground", "Sets the default background color to use in drawing methods, transparent by default")] public void SetDefaultBackgroundColor(Color color) { - DefaultBackground = color; + _defaultBackground = color; } - [LuaMethodAttributes( - "defaultTextBackground", - "Sets the default backgroiund color to use in text drawing methods, half-transparent black by default" - )] + [LuaMethodAttributes("defaultTextBackground", "Sets the default backgroiund color to use in text drawing methods, half-transparent black by default")] public void SetDefaultTextBackground(Color color) { - DefaultTextBackground = color; + _defaultTextBackground = color; } [LuaMethodAttributes( - "defaultPixelFont", - "Sets the default font to use in gui.pixelText(). Two font families are available, \"fceux\" and \"gens\" (or \"0\" and \"1\" respectively), \"gens\" is used by default" - )] + "defaultPixelFont", "Sets the default font to use in gui.pixelText(). Two font families are available, \"fceux\" and \"gens\" (or \"0\" and \"1\" respectively), \"gens\" is used by default")] public void SetDefaultTextBackground(string fontfamily) { switch (fontfamily) { case "fceux": case "0": - DefaultPixelFont = 0; + _defaultPixelFont = 0; break; case "gens": case "1": - DefaultPixelFont = 1; + _defaultPixelFont = 1; break; default: - Log(string.Format("Unable to find font family: {0}", fontfamily)); + Log($"Unable to find font family: {fontfamily}"); return; } } - - - [LuaMethodAttributes( - "drawBezier", - "Draws a Bezier curve using the table of coordinates provided in the given color" - )] + [LuaMethodAttributes("drawBezier", "Draws a Bezier curve using the table of coordinates provided in the given color")] public void DrawBezier(LuaTable points, Color color) { using (var g = GetGraphics()) @@ -249,9 +214,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "drawBox", - "Draws a rectangle on screen from x1/y1 to x2/y2. Same as drawRectangle except it receives two points intead of a point and width/height" - )] + "drawBox", "Draws a rectangle on screen from x1/y1 to x2/y2. Same as drawRectangle except it receives two points intead of a point and width/height")] public void DrawBox(int x, int y, int x2, int y2, Color? line = null, Color? background = null) { using (var g = GetGraphics()) @@ -278,9 +241,9 @@ namespace BizHawk.Client.EmuHawk y -= y2; } - g.DrawRectangle(GetPen(line ?? DefaultForeground), x, y, x2, y2); + g.DrawRectangle(GetPen(line ?? _defaultForeground), x, y, x2, y2); - var bg = background ?? DefaultBackground; + var bg = background ?? _defaultBackground; if (bg.HasValue) { g.FillRectangle(GetBrush(bg.Value), x + 1, y + 1, x2 - 1, y2 - 1); @@ -295,23 +258,21 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "drawEllipse", - "Draws an ellipse at the given coordinates and the given width and height. Line is the color of the ellipse. Background is the optional fill color" - )] + "drawEllipse", "Draws an ellipse at the given coordinates and the given width and height. Line is the color of the ellipse. Background is the optional fill color")] public void DrawEllipse(int x, int y, int width, int height, Color? line = null, Color? background = null) { using (var g = GetGraphics()) { try { - var bg = background ?? DefaultBackground; + var bg = background ?? _defaultBackground; if (bg.HasValue) { var brush = GetBrush(bg.Value); g.FillEllipse(brush, x, y, width, height); } - g.DrawEllipse(GetPen(line ?? DefaultForeground), x, y, width, height); + g.DrawEllipse(GetPen(line ?? _defaultForeground), x, y, width, height); } catch (Exception) { @@ -322,9 +283,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "drawIcon", - "draws an Icon (.ico) file from the given path at the given coordinate. width and height are optional. If specified, it will resize the image accordingly" - )] + "drawIcon", "draws an Icon (.ico) file from the given path at the given coordinate. width and height are optional. If specified, it will resize the image accordingly")] public void DrawIcon(string path, int x, int y, int? width = null, int? height = null) { using (var g = GetGraphics()) @@ -350,13 +309,9 @@ namespace BizHawk.Client.EmuHawk } } - private readonly Dictionary ImageCache = new Dictionary(); - [LuaMethodAttributes( - "drawImage", - "draws an image file from the given path at the given coordinate. width and height are optional. If specified, it will resize the image accordingly" - )] - public void DrawImage(string path, int x, int y, int? width = null, int? height = null) + "drawImage", "draws an image file from the given path at the given coordinate. width and height are optional. If specified, it will resize the image accordingly")] + public void DrawImage(string path, int x, int y, int? width = null, int? height = null, bool cache = true) { if (!File.Exists(path)) { @@ -367,14 +322,17 @@ namespace BizHawk.Client.EmuHawk using (var g = GetGraphics()) { Image img; - if (ImageCache.ContainsKey(path)) + if (_imageCache.ContainsKey(path)) { - img = ImageCache[path]; + img = _imageCache[path]; } else { img = Image.FromFile(path); - ImageCache.Add(path, img); + if (cache) + { + _imageCache.Add(path, img); + } } g.DrawImage(img, x, y, width ?? img.Width, height ?? img.Height); @@ -382,9 +340,19 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "drawImageRegion", - "draws a given region of an image file from the given path at the given coordinate, and optionally with the given size" - )] + "clearImageCache", "clears the image cache that is built up by using gui.drawImage, also releases the file handle for cached images")] + public void ClearImageCache() + { + foreach (var image in _imageCache) + { + image.Value.Dispose(); + } + + _imageCache.Clear(); + } + + [LuaMethodAttributes( + "drawImageRegion", "draws a given region of an image file from the given path at the given coordinate, and optionally with the given size")] public void DrawImageRegion(string path, int source_x, int source_y, int source_width, int source_height, int dest_x, int dest_y, int? dest_width = null, int? dest_height = null) { if (!File.Exists(path)) @@ -396,50 +364,40 @@ namespace BizHawk.Client.EmuHawk using (var g = GetGraphics()) { Image img; - if (ImageCache.ContainsKey(path)) + if (_imageCache.ContainsKey(path)) { - img = ImageCache[path]; + img = _imageCache[path]; } else { img = Image.FromFile(path); - ImageCache.Add(path, img); + _imageCache.Add(path, img); } - var dest_rect = new Rectangle(dest_x, dest_y, (dest_width ?? source_width), (dest_height ?? source_height)); + var destRect = new Rectangle(dest_x, dest_y, dest_width ?? source_width, dest_height ?? source_height); - g.DrawImage(img, dest_rect, source_x, source_y, source_width, source_height, GraphicsUnit.Pixel); + g.DrawImage(img, destRect, source_x, source_y, source_width, source_height, GraphicsUnit.Pixel); } } [LuaMethodAttributes( - "drawLine", - "Draws a line from the first coordinate pair to the 2nd. Color is optional (if not specified it will be drawn black)" - )] + "drawLine", "Draws a line from the first coordinate pair to the 2nd. Color is optional (if not specified it will be drawn black)")] public void DrawLine(int x1, int y1, int x2, int y2, Color? color = null) { using (var g = GetGraphics()) { - g.DrawLine(GetPen(color ?? DefaultForeground), x1, y1, x2, y2); + g.DrawLine(GetPen(color ?? _defaultForeground), x1, y1, x2, y2); } } - [LuaMethodAttributes( - "drawAxis", - "Draws an axis of the specified size at the coordinate pair.)" - )] - + [LuaMethodAttributes("drawAxis", "Draws an axis of the specified size at the coordinate pair.)")] public void DrawAxis(int x, int y, int size, Color? color = null) { DrawLine(x + size, y, x - size, y, color); DrawLine(x, y + size, x, y - size, color); } - - [LuaMethodAttributes( - "drawPie", - "draws a Pie shape at the given coordinates and the given width and height" - )] + [LuaMethodAttributes("drawPie", "draws a Pie shape at the given coordinates and the given width and height")] public void DrawPie( int x, int y, @@ -452,29 +410,26 @@ namespace BizHawk.Client.EmuHawk { using (var g = GetGraphics()) { - var bg = background ?? DefaultBackground; + var bg = background ?? _defaultBackground; if (bg.HasValue) { var brush = GetBrush(bg.Value); g.FillPie(brush, x, y, width, height, startangle, sweepangle); } - g.DrawPie(GetPen(line ?? DefaultForeground), x + 1, y + 1, width - 1, height - 1, startangle, sweepangle); - + g.DrawPie(GetPen(line ?? _defaultForeground), x + 1, y + 1, width - 1, height - 1, startangle, sweepangle); } } [LuaMethodAttributes( - "drawPixel", - "Draws a single pixel at the given coordinates in the given color. Color is optional (if not specified it will be drawn black)" - )] + "drawPixel", "Draws a single pixel at the given coordinates in the given color. Color is optional (if not specified it will be drawn black)")] public void DrawPixel(int x, int y, Color? color = null) { using (var g = GetGraphics()) { try { - g.DrawLine(GetPen(color ?? DefaultForeground), x, y, x + 0.1F, y); + g.DrawLine(GetPen(color ?? _defaultForeground), x, y, x + 0.1F, y); } catch (Exception) { @@ -484,9 +439,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "drawPolygon", - "Draws a polygon using the table of coordinates specified in points. This should be a table of tables(each of size 2). Line is the color of the polygon. Background is the optional fill color" - )] + "drawPolygon", "Draws a polygon using the table of coordinates specified in points. This should be a table of tables(each of size 2). Line is the color of the polygon. Background is the optional fill color")] public void DrawPolygon(LuaTable points, Color? line = null, Color? background = null) { using (var g = GetGraphics()) @@ -501,8 +454,8 @@ namespace BizHawk.Client.EmuHawk i++; } - g.DrawPolygon(GetPen(line ?? DefaultForeground), pointsArr); - var bg = background ?? DefaultBackground; + g.DrawPolygon(GetPen(line ?? _defaultForeground), pointsArr); + var bg = background ?? _defaultBackground; if (bg.HasValue) { g.FillPolygon(GetBrush(bg.Value), pointsArr); @@ -516,15 +469,13 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "drawRectangle", - "Draws a rectangle at the given coordinate and the given width and height. Line is the color of the box. Background is the optional fill color" - )] + "drawRectangle", "Draws a rectangle at the given coordinate and the given width and height. Line is the color of the box. Background is the optional fill color")] public void DrawRectangle(int x, int y, int width, int height, Color? line = null, Color? background = null) { using (var g = GetGraphics()) { - g.DrawRectangle(GetPen(line ?? DefaultForeground), x, y, width, height); - var bg = background ?? DefaultBackground; + g.DrawRectangle(GetPen(line ?? _defaultForeground), x, y, width, height); + var bg = background ?? _defaultBackground; if (bg.HasValue) { g.FillRectangle(GetBrush(bg.Value), x + 1, y + 1, width - 1, height - 1); @@ -532,10 +483,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "drawString", - "Alias of gui.drawText()" - )] + [LuaMethodAttributes("drawString", "Alias of gui.drawText()")] public void DrawString( int x, int y, @@ -552,9 +500,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "drawText", - "Draws the given message in the emulator screen space (like all draw functions) at the given x,y coordinates and the given color. The default color is white. A fontfamily can be specified and is monospace generic if none is specified (font family options are the same as the .NET FontFamily class). The fontsize default is 12. The default font style is regular. Font style options are regular, bold, italic, strikethrough, underline. Horizontal alignment options are left (default), center, or right. Vertical alignment options are bottom (default), middle, or top. Alignment options specify which ends of the text will be drawn at the x and y coordinates." - )] + "drawText", "Draws the given message in the emulator screen space (like all draw functions) at the given x,y coordinates and the given color. The default color is white. A fontfamily can be specified and is monospace generic if none is specified (font family options are the same as the .NET FontFamily class). The fontsize default is 12. The default font style is regular. Font style options are regular, bold, italic, strikethrough, underline. Horizontal alignment options are left (default), center, or right. Vertical alignment options are bottom (default), middle, or top. Alignment options specify which ends of the text will be drawn at the x and y coordinates.")] public void DrawText( int x, int y, @@ -602,7 +548,7 @@ namespace BizHawk.Client.EmuHawk // The text isn't written out using GenericTypographic, so measuring it using GenericTypographic seemed to make it worse. // And writing it out with GenericTypographic just made it uglier. :p - StringFormat f = new StringFormat(StringFormat.GenericDefault); + var f = new StringFormat(StringFormat.GenericDefault); var font = new Font(family, fontsize ?? 12, fstyle, GraphicsUnit.Pixel); Size sizeOfText = g.MeasureString(message, font, 0, f).ToSize(); if (horizalign != null) @@ -620,6 +566,7 @@ namespace BizHawk.Client.EmuHawk break; } } + if (vertalign != null) { switch (vertalign.ToLower()) @@ -635,10 +582,11 @@ namespace BizHawk.Client.EmuHawk break; } } + Rectangle rect = new Rectangle(new Point(x, y), sizeOfText); - g.FillRectangle(GetBrush(backcolor ?? DefaultTextBackground.Value), rect); + g.FillRectangle(GetBrush(backcolor ?? _defaultTextBackground.Value), rect); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; - g.DrawString(message, font, GetBrush(forecolor ?? DefaultForeground), x, y); + g.DrawString(message, font, GetBrush(forecolor ?? _defaultForeground), x, y); } catch (Exception) { @@ -649,8 +597,7 @@ namespace BizHawk.Client.EmuHawk [LuaMethodAttributes( "pixelText", - "Draws the given message in the emulator screen space (like all draw functions) at the given x,y coordinates and the given color. The default color is white. Two font families are available, \"fceux\" and \"gens\" (or \"0\" and \"1\" respectively), both are monospace and have the same size as in the emulaors they've been taken from. If no font family is specified, it uses \"gens\" font, unless that's overridden via gui.defaultPixelFont()" - )] + "Draws the given message in the emulator screen space (like all draw functions) at the given x,y coordinates and the given color. The default color is white. Two font families are available, \"fceux\" and \"gens\" (or \"0\" and \"1\" respectively), both are monospace and have the same size as in the emulaors they've been taken from. If no font family is specified, it uses \"gens\" font, unless that's overridden via gui.defaultPixelFont()")] public void DrawText( int x, int y, @@ -666,7 +613,7 @@ namespace BizHawk.Client.EmuHawk var index = 0; if (string.IsNullOrEmpty(fontfamily)) { - index = DefaultPixelFont; + index = _defaultPixelFont; } else { @@ -681,20 +628,21 @@ namespace BizHawk.Client.EmuHawk index = 1; break; default: - Log(string.Format("Unable to find font family: {0}", fontfamily)); + Log($"Unable to find font family: {fontfamily}"); return; } } - StringFormat f = new StringFormat(StringFormat.GenericTypographic) + + var f = new StringFormat(StringFormat.GenericTypographic) { FormatFlags = StringFormatFlags.MeasureTrailingSpaces }; var font = new Font(GlobalWin.DisplayManager.CustomFonts.Families[index], 8, FontStyle.Regular, GraphicsUnit.Pixel); Size sizeOfText = g.MeasureString(message, font, 0, f).ToSize(); - Rectangle rect = new Rectangle(new Point(x, y), sizeOfText + new Size(1, 0)); - g.FillRectangle(GetBrush(backcolor ?? DefaultTextBackground.Value), rect); + var rect = new Rectangle(new Point(x, y), sizeOfText + new Size(1, 0)); + g.FillRectangle(GetBrush(backcolor ?? _defaultTextBackground.Value), rect); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; - g.DrawString(message, font, GetBrush(forecolor ?? DefaultForeground), x, y); + g.DrawString(message, font, GetBrush(forecolor ?? _defaultForeground), x, y); } catch (Exception) { @@ -704,9 +652,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "text", - "Displays the given text on the screen at the given coordinates. Optional Foreground color. The optional anchor flag anchors the text to one of the four corners. Anchor flag parameters: topleft, topright, bottomleft, bottomright" - )] + "text", "Displays the given text on the screen at the given coordinates. Optional Foreground color. The optional anchor flag anchors the text to one of the four corners. Anchor flag parameters: topleft, topright, bottomleft, bottomright")] public void Text( int x, int y, @@ -747,10 +693,7 @@ namespace BizHawk.Client.EmuHawk GlobalWin.OSD.AddGUIText(message, x, y, Color.Black, forecolor ?? Color.White, a); } - [LuaMethodAttributes( - "createcanvas", - "Creates a canvas of the given size." - )] + [LuaMethodAttributes("createcanvas", "Creates a canvas of the given size.")] public LuaTable Text(int width, int height) { var canvas = new LuaCanvas(width, height); diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Input.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Input.cs index ddc95fde91..5d7fd0181c 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Input.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Input.cs @@ -15,12 +15,10 @@ namespace BizHawk.Client.EmuHawk public InputLuaLibrary(Lua lua, Action logOutputCallback) : base(lua, logOutputCallback) { } - public override string Name { get { return "input"; } } + public override string Name => "input"; [LuaMethodAttributes( - "get", - "Returns a lua table of all the buttons the user is currently pressing on their keyboard and gamepads\nAll buttons that are pressed have their key values set to true; all others remain nil." - )] + "get", "Returns a lua table of all the buttons the user is currently pressing on their keyboard and gamepads\nAll buttons that are pressed have their key values set to true; all others remain nil.")] public LuaTable Get() { var buttons = Lua.NewTable(); @@ -33,13 +31,12 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "getmouse", - "Returns a lua table of the mouse X/Y coordinates and button states. Table keys are X, Y, Left, Middle, Right, XButton1, XButton2, Wheel." - )] + "getmouse", "Returns a lua table of the mouse X/Y coordinates and button states. Table keys are X, Y, Left, Middle, Right, XButton1, XButton2, Wheel.")] public LuaTable GetMouse() { var buttons = Lua.NewTable(); - //TODO - need to specify whether in "emu" or "native" coordinate space. + + // TODO - need to specify whether in "emu" or "native" coordinate space. var p = GlobalWin.DisplayManager.UntransformPoint(Control.MousePosition); buttons["X"] = p.X; buttons["Y"] = p.Y; diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Savestate.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Savestate.cs index 3256530e83..da57f93105 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Savestate.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Savestate.cs @@ -15,17 +15,14 @@ namespace BizHawk.Client.EmuHawk public SavestateLuaLibrary(Lua lua, Action logOutputCallback) : base(lua, logOutputCallback) { } - public override string Name { get { return "savestate"; } } + public override string Name => "savestate"; - [LuaMethodAttributes( - "load", - "Loads a savestate with the given path" - )] + [LuaMethodAttributes("load", "Loads a savestate with the given path")] public void Load(string path) { if (!File.Exists(path)) { - Log(string.Format("could not find file: {0}", path)); + Log($"could not find file: {path}"); } else { @@ -33,10 +30,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "loadslot", - "Loads the savestate at the given slot number (must be an integer between 0 and 9)" - )] + [LuaMethodAttributes("loadslot", "Loads the savestate at the given slot number (must be an integer between 0 and 9)")] public void LoadSlot(int slotNum) { if (slotNum >= 0 && slotNum <= 9) @@ -45,19 +39,13 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "save", - "Saves a state at the given path" - )] + [LuaMethodAttributes("save", "Saves a state at the given path")] public void Save(string path) { GlobalWin.MainForm.SaveState(path, path, true); } - [LuaMethodAttributes( - "saveslot", - "Saves a state at the given save slot (must be an integer between 0 and 9)" - )] + [LuaMethodAttributes("saveslot", "Saves a state at the given save slot (must be an integer between 0 and 9)")] public void SaveSlot(int slotNum) { if (slotNum >= 0 && slotNum <= 9) diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Tastudio.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Tastudio.cs index a678679a7a..e51e4b9b76 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Tastudio.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.Tastudio.cs @@ -1,10 +1,10 @@ using System; using System.ComponentModel; - -using BizHawk.Client.Common; -using LuaInterface; using System.Drawing; +using LuaInterface; +using BizHawk.Client.Common; + namespace BizHawk.Client.EmuHawk { [Description("A library for manipulating the Tastudio dialog of the EmuHawk client")] @@ -17,58 +17,38 @@ namespace BizHawk.Client.EmuHawk public TastudioLuaLibrary(Lua lua, Action logOutputCallback) : base(lua, logOutputCallback) { } - public override string Name { get { return "tastudio"; } } + public override string Name => "tastudio"; - private TAStudio Tastudio - { - get - { - return GlobalWin.Tools.Get() as TAStudio; - } - } + private TAStudio Tastudio => GlobalWin.Tools.Get() as TAStudio; - - [LuaMethodAttributes( - "engaged", - "returns whether or not tastudio is currently engaged (active)" - )] + [LuaMethodAttributes("engaged", "returns whether or not tastudio is currently engaged (active)")] public bool Engaged() { return GlobalWin.Tools.Has(); // TODO: eventually tastudio should have an engaged flag } - [LuaMethodAttributes( - "getrecording", - "returns whether or not TAStudio is in recording mode" - )] + [LuaMethodAttributes("getrecording", "returns whether or not TAStudio is in recording mode")] public bool GetRecording() { return Tastudio.TasPlaybackBox.RecordingMode; } - [LuaMethodAttributes( - "setrecording", - "sets the recording mode on/off depending on the parameter" - )] + [LuaMethodAttributes("setrecording", "sets the recording mode on/off depending on the parameter")] public void SetRecording(bool val) { if (Tastudio.TasPlaybackBox.RecordingMode != val) + { Tastudio.ToggleReadOnly(); + } } - [LuaMethodAttributes( - "togglerecording", - "toggles tastudio recording mode on/off depending on its current state" - )] + [LuaMethodAttributes("togglerecording", "toggles tastudio recording mode on/off depending on its current state")] public void SetRecording() { Tastudio.ToggleReadOnly(); } - [LuaMethodAttributes( - "setbranchtext", - "adds the given message to the existing branch, or to the branch that will be created next if branch index is not specified" - )] + [LuaMethodAttributes("setbranchtext", "adds the given message to the existing branch, or to the branch that will be created next if branch index is not specified")] public void SetBranchText(string text, int? index = null) { if (index != null) @@ -81,10 +61,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "getmarker", - "returns the marker text at the given frame, or an empty string if there is no marker for the given frame" - )] + [LuaMethodAttributes("getmarker", "returns the marker text at the given frame, or an empty string if there is no marker for the given frame")] public string GetMarker(int frame) { if (Engaged()) @@ -99,10 +76,7 @@ namespace BizHawk.Client.EmuHawk return ""; } - [LuaMethodAttributes( - "removemarker", - "if there is a marker for the given frame, it will be removed" - )] + [LuaMethodAttributes("removemarker", "if there is a marker for the given frame, it will be removed")] public void RemoveMarker(int frame) { if (Engaged()) @@ -116,10 +90,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "setmarker", - "Adds or sets a marker at the given frame, with an optional message" - )] + [LuaMethodAttributes("setmarker", "Adds or sets a marker at the given frame, with an optional message")] public void SetMarker(int frame, string message = null) { if (Engaged()) @@ -137,10 +108,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "islag", - "Returns whether or not the given frame was a lag frame, null if unknown" - )] + [LuaMethodAttributes("islag", "Returns whether or not the given frame was a lag frame, null if unknown")] public bool? IsLag(int frame) { if (Engaged()) @@ -154,10 +122,7 @@ namespace BizHawk.Client.EmuHawk return null; } - [LuaMethodAttributes( - "setlag", - "Sets the lag information for the given frame, if the frame does not exist in the lag log, it will be added. If the value is null, the lag information for that frame will be removed" - )] + [LuaMethodAttributes("setlag", "Sets the lag information for the given frame, if the frame does not exist in the lag log, it will be added. If the value is null, the lag information for that frame will be removed")] public void SetLag(int frame, bool? value) { if (Engaged()) @@ -166,10 +131,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "hasstate", - "Returns whether or not the given frame has a savestate associated with it" - )] + [LuaMethodAttributes("hasstate", "Returns whether or not the given frame has a savestate associated with it")] public bool HasState(int frame) { if (Engaged()) @@ -183,33 +145,36 @@ namespace BizHawk.Client.EmuHawk return false; } - [LuaMethodAttributes( - "setplayback", - "Seeks the given frame (a number) or marker (a string)" - )] + [LuaMethodAttributes("setplayback", "Seeks the given frame (a number) or marker (a string)")] public void SetPlayback(object frame) { if (Engaged()) { int f; - if (frame is double) f = (int)(double)frame; + if (frame is double) + { + f = (int)(double)frame; + } else { f = Tastudio.CurrentTasMovie.Markers.FindIndex((string)frame); - if (f == -1) return; + if (f == -1) + { + return; + } + f = Tastudio.CurrentTasMovie.Markers[f].Frame; } - if (f < Tastudio.CurrentTasMovie.InputLogLength && f>=0) + + if (f < Tastudio.CurrentTasMovie.InputLogLength && f >= 0) { - Tastudio.GoToFrame(f,true); + Tastudio.GoToFrame(f, true); } } } [LuaMethodAttributes( - "onqueryitembg", - "called during the background draw event of the tastudio listview. luaf must be a function that takes 2 params: index, column. The first is the integer row index of the listview, and the 2nd is the string column name. luaf should return a value that can be parsed into a .NET Color object (string color name, or integer value)" - )] + "onqueryitembg", "called during the background draw event of the tastudio listview. luaf must be a function that takes 2 params: index, column. The first is the integer row index of the listview, and the 2nd is the string column name. luaf should return a value that can be parsed into a .NET Color object (string color name, or integer value)")] public void OnQueryItemBg(LuaFunction luaf) { if (Engaged()) @@ -230,9 +195,7 @@ namespace BizHawk.Client.EmuHawk } [LuaMethodAttributes( - "onqueryitemtext", - "called during the text draw event of the tastudio listview. luaf must be a function that takes 2 params: index, column. The first is the integer row index of the listview, and the 2nd is the string column name. luaf should return a value that can be parsed into a .NET Color object (string color name, or integer value)" - )] + "onqueryitemtext", "called during the text draw event of the tastudio listview. luaf must be a function that takes 2 params: index, column. The first is the integer row index of the listview, and the 2nd is the string column name. luaf should return a value that can be parsed into a .NET Color object (string color name, or integer value)")] public void OnQueryItemText(LuaFunction luaf) { if (Engaged()) @@ -241,23 +204,13 @@ namespace BizHawk.Client.EmuHawk { var result = luaf.Call(index, name); - if (result != null) - { - if (result[0] != null) - { - return result[0].ToString(); - } - } - - return (string)null; + return result?[0]?.ToString(); }; } } [LuaMethodAttributes( - "onqueryitemicon", - "called during the icon draw event of the tastudio listview. luaf must be a function that takes 2 params: index, column. The first is the integer row index of the listview, and the 2nd is the string column name. luaf should return a value that can be parsed into a .NET Color object (string color name, or integer value)" - )] + "onqueryitemicon", "called during the icon draw event of the tastudio listview. luaf must be a function that takes 2 params: index, column. The first is the integer row index of the listview, and the 2nd is the string column name. luaf should return a value that can be parsed into a .NET Color object (string color name, or integer value)")] public void OnQueryItemIcon(LuaFunction luaf) { if (Engaged()) @@ -265,17 +218,11 @@ namespace BizHawk.Client.EmuHawk Tastudio.QueryItemIconCallback = (int index, string name) => { var result = luaf.Call(index, name); - if (result != null) + if (result?[0] != null) { - if (result[0] != null) - { - string path = result[0].ToString(); - Icon icon = new Icon(path); - if (icon != null) - { - return icon.ToBitmap(); - } - } + string path = result[0].ToString(); + Icon icon = new Icon(path); + return icon.ToBitmap(); } return (Bitmap)null; @@ -283,10 +230,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "ongreenzoneinvalidated", - "called whenever the greenzone is invalidated and returns the first frame that was invalidated" - )] + [LuaMethodAttributes("ongreenzoneinvalidated", "called whenever the greenzone is invalidated and returns the first frame that was invalidated")] public void OnGreenzoneInvalidated(LuaFunction luaf) { if (Engaged()) @@ -298,10 +242,7 @@ namespace BizHawk.Client.EmuHawk } } - [LuaMethodAttributes( - "getselection", - "gets the currently selected frames" - )] + [LuaMethodAttributes("getselection", "gets the currently selected frames")] public LuaTable GetSelection() { LuaTable table = Lua.NewTable(); @@ -319,10 +260,7 @@ namespace BizHawk.Client.EmuHawk return table; } - [LuaMethodAttributes( - "insertframes", - "inserts the given number of blank frames at the given insertion frame" - )] + [LuaMethodAttributes("insertframes", "inserts the given number of blank frames at the given insertion frame")] public void InsertNumFrames(int insertionFrame, int numberOfFrames) { if (Engaged()) @@ -333,15 +271,12 @@ namespace BizHawk.Client.EmuHawk } else { - Log(insertionFrame.ToString() + " is out of range"); + Log(insertionFrame + " is out of range"); } } } - [LuaMethodAttributes( - "deleteframes", - "deletes the given number of blank frames beginning at the given frame" - )] + [LuaMethodAttributes("deleteframes", "deletes the given number of blank frames beginning at the given frame")] public void DeleteFrames(int beginningFrame, int numberOfFrames) { if (Engaged()) @@ -352,7 +287,7 @@ namespace BizHawk.Client.EmuHawk } else { - Log(beginningFrame.ToString() + " is out of range"); + Log(beginningFrame + " is out of range"); } } } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.cs b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.cs index 8fdd16490a..b9d1ea133f 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/Libraries/EmuLuaLibrary.cs @@ -15,37 +15,12 @@ namespace BizHawk.Client.EmuHawk { public class EmuLuaLibrary { - private readonly Dictionary Libraries = new Dictionary(); - - private Lua _lua = new Lua(); - private Lua _currThread; - public EmuLuaLibrary() { Docs = new LuaDocumentation(); _lua["keepalives"] = _lua.NewTable(); } - private FormsLuaLibrary FormsLibrary - { - get { return (FormsLuaLibrary)Libraries[typeof(FormsLuaLibrary)]; } - } - - private EventLuaLibrary EventsLibrary - { - get { return (EventLuaLibrary)Libraries[typeof(EventLuaLibrary)]; } - } - - private EmulatorLuaLibrary EmulatorLuaLibrary - { - get { return (EmulatorLuaLibrary)Libraries[typeof(EmulatorLuaLibrary)]; } - } - - public GuiLuaLibrary GuiLibrary - { - get { return (GuiLuaLibrary)Libraries[typeof(GuiLuaLibrary)]; } - } - public EmuLuaLibrary(IEmulatorServiceProvider serviceProvider) : this() { @@ -67,8 +42,7 @@ namespace BizHawk.Client.EmuHawk .GetTypes() .Where(t => typeof(LuaLibraryBase).IsAssignableFrom(t)) .Where(t => t.IsSealed) - .Where(t => ServiceInjector.IsAvailable(serviceProvider, t)) - ); + .Where(t => ServiceInjector.IsAvailable(serviceProvider, t))); foreach (var lib in libs) { @@ -96,7 +70,6 @@ namespace BizHawk.Client.EmuHawk // Add LuaCanvas to Docs Type luaCanvas = typeof(LuaCanvas); - var luaAttr = typeof(LuaMethodAttributes); var methods = luaCanvas .GetMethods() @@ -104,13 +77,31 @@ namespace BizHawk.Client.EmuHawk foreach (var method in methods) { - var luaMethodAttr = method.GetCustomAttributes(luaAttr, false).First() as LuaMethodAttributes; - var luaName = "(Canvas)." + luaMethodAttr.Name; - Docs.Add(new LibraryFunction(nameof(LuaCanvas), luaCanvas.Description(), method)); } } + public bool IsRebootingCore { get; set; } // pretty hacky.. we dont want a lua script to be able to restart itself by rebooting the core + + private readonly Dictionary Libraries = new Dictionary(); + public LuaFileList ScriptList { get; } = new LuaFileList(); + + public IEnumerable RunningScripts + { + get { return ScriptList.Where(lf => lf.Enabled); } + } + + private Lua _lua = new Lua(); + private Lua _currThread; + + private FormsLuaLibrary FormsLibrary => (FormsLuaLibrary)Libraries[typeof(FormsLuaLibrary)]; + + private EventLuaLibrary EventsLibrary => (EventLuaLibrary)Libraries[typeof(EventLuaLibrary)]; + + private EmulatorLuaLibrary EmulatorLuaLibrary => (EmulatorLuaLibrary)Libraries[typeof(EmulatorLuaLibrary)]; + + public GuiLuaLibrary GuiLibrary => (GuiLuaLibrary)Libraries[typeof(GuiLuaLibrary)]; + public void Restart(IEmulatorServiceProvider newServiceProvider) { foreach (var lib in Libraries) @@ -119,15 +110,28 @@ namespace BizHawk.Client.EmuHawk } } - public LuaDocumentation Docs { get; private set; } + public void StartLuaDrawing() + { + if (ScriptList.Any() && GuiLibrary.SurfaceIsNull) + { + GuiLibrary.DrawNew("emu"); + } + } + + public void EndLuaDrawing() + { + if (ScriptList.Any()) + { + GuiLibrary.DrawFinish(); + } + } + + public LuaDocumentation Docs { get; } public bool IsRunning { get; set; } public EventWaitHandle LuaWait { get; private set; } public bool FrameAdvanceRequested { get; private set; } - public LuaFunctionList RegisteredFunctions - { - get { return EventsLibrary.RegisteredFunctions; } - } + public LuaFunctionList RegisteredFunctions => EventsLibrary.RegisteredFunctions; public void WindowClosed(IntPtr handle) { @@ -196,7 +200,8 @@ namespace BizHawk.Client.EmuHawk var execResult = script.Resume(0); _lua.RunScheduledDisposes(); - //not sure how this is going to work out, so do this too + + // not sure how this is going to work out, so do this too script.RunScheduledDisposes(); _currThread = null; diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaAutocompleteInstaller.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaAutocompleteInstaller.cs index 782f043cbc..2c55692107 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaAutocompleteInstaller.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaAutocompleteInstaller.cs @@ -1,11 +1,5 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using Newtonsoft.Json; - -using BizHawk.Client.Common; namespace BizHawk.Client.EmuHawk { @@ -17,7 +11,7 @@ namespace BizHawk.Client.EmuHawk public bool IsInstalled(TextEditors editor) { - switch(editor) + switch (editor) { case TextEditors.Sublime2: return IsSublimeInstalled(); @@ -43,7 +37,7 @@ namespace BizHawk.Client.EmuHawk public void InstallBizLua(TextEditors editor) { - switch(editor) + switch (editor) { case TextEditors.Sublime2: InstallBizLuaToSublime2(); @@ -56,10 +50,7 @@ namespace BizHawk.Client.EmuHawk #endregion - private string AppDataFolder - { - get { return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); } - } + private string AppDataFolder => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); private bool IsSublimeInstalled() { diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaButton.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaButton.cs index 06b17c0551..3b39e74645 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaButton.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaButton.cs @@ -3,12 +3,12 @@ using System.Windows.Forms; namespace BizHawk.Client.EmuHawk { - class LuaButton : Button + internal class LuaButton : Button { private void DoLuaClick(object sender, EventArgs e) { LuaWinform parent = Parent as LuaWinform; - if (parent != null) parent.DoLuaEvent(Handle); + parent?.DoLuaEvent(Handle); } protected override void OnClick(EventArgs e) diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs index 80fbc61a60..81990c0b9d 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaCanvas.cs @@ -9,7 +9,7 @@ namespace BizHawk.Client.EmuHawk [Description("Represents a canvas object returned by the gui.createcanvas() method")] public partial class LuaCanvas : Form { - private Graphics graphics; + private readonly Graphics _graphics; public LuaCanvas(int width, int height) { @@ -17,7 +17,7 @@ namespace BizHawk.Client.EmuHawk pictureBox.Width = width; pictureBox.Height = height; pictureBox.Image = new Bitmap(width, height); - graphics = Graphics.FromImage(pictureBox.Image); + _graphics = Graphics.FromImage(pictureBox.Image); } [LuaMethodAttributes("SetTitle", "Sets the canvas window title")] @@ -29,7 +29,7 @@ namespace BizHawk.Client.EmuHawk [LuaMethodAttributes("Clear", "Clears the canvas")] public void Clear(Color color) { - graphics.Clear(color); + _graphics.Clear(color); } [LuaMethodAttributes("Refresh", "Redraws the canvas")] @@ -46,11 +46,11 @@ namespace BizHawk.Client.EmuHawk if (fill.HasValue) { var brush = new SolidBrush(fill.Value); - graphics.FillRectangle(brush, x, y, width, height); + _graphics.FillRectangle(brush, x, y, width, height); } var pen = new Pen(outline.HasValue ? outline.Value : Color.Black); - graphics.DrawRectangle(pen, x, y, width, height); + _graphics.DrawRectangle(pen, x, y, width, height); } [LuaMethodAttributes( @@ -88,8 +88,8 @@ namespace BizHawk.Client.EmuHawk } var font = new Font(family, fontsize ?? 12, fstyle, GraphicsUnit.Pixel); - graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; - graphics.DrawString(message, font, new SolidBrush(color ?? Color.White), x, y); + _graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; + _graphics.DrawString(message, font, new SolidBrush(color ?? Color.White), x, y); } } } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaCheckbox.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaCheckbox.cs index 6c75e0a9c0..17ee26082f 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaCheckbox.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaCheckbox.cs @@ -8,10 +8,7 @@ namespace BizHawk.Client.EmuHawk private void DoLuaClick(object sender, EventArgs e) { var parent = Parent as LuaWinform; - if (parent != null) - { - parent.DoLuaEvent(Handle); - } + parent?.DoLuaEvent(Handle); } protected override void OnClick(EventArgs e) diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs index 829d8e8062..1b0994ffd4 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaConsole.cs @@ -19,15 +19,12 @@ namespace BizHawk.Client.EmuHawk [RequiredService] private IEmulator Emulator { get; set; } - private readonly LuaFileList _luaList; private bool _sortReverse; private string _lastColumnSorted; private readonly List _consoleCommandHistory = new List(); private int _consoleCommandHistoryIndex = -1; - public bool IsRebootingCore { get; set; } - public ToolDialogSettings.ColumnList Columns { get; set; } public class LuaConsoleSettings @@ -52,11 +49,6 @@ namespace BizHawk.Client.EmuHawk Settings = new LuaConsoleSettings(); _sortReverse = false; _lastColumnSorted = ""; - _luaList = new LuaFileList - { - ChangedCallback = SessionChangedCallback, - LoadCallback = ClearOutputWindow - }; InitializeComponent(); @@ -92,7 +84,7 @@ namespace BizHawk.Client.EmuHawk private IEnumerable SelectedItems { - get { return LuaListView.SelectedIndices().Select(index => _luaList[index]); } + get { return LuaListView.SelectedIndices().Select(index => LuaImp.ScriptList[index]); } } private IEnumerable SelectedFiles @@ -122,9 +114,12 @@ namespace BizHawk.Client.EmuHawk private void LuaConsole_Load(object sender, EventArgs e) { + LuaImp.ScriptList.ChangedCallback = SessionChangedCallback; + LuaImp.ScriptList.LoadCallback = ClearOutputWindow; + if (Global.Config.RecentLuaSession.AutoLoad && !Global.Config.RecentLuaSession.Empty) { - LoadSessionFromRecent(Global.Config.RecentLuaSession.MostRecent); + LoadSessionFromRecent(Global.Config.RecentLuaSession.MostRecent); } else if (Global.Config.RecentLua.AutoLoad) { @@ -139,37 +134,50 @@ namespace BizHawk.Client.EmuHawk public void Restart() { - // Even if the lua console is self-rebooting from client.reboot_core() we still want to re-inject dependencies - if (IsRebootingCore) + List runningScripts = new List(); + + if (LuaImp != null) // Things we need to do with the existing LuaImp before we can make a new one { - LuaImp.Restart(Emulator.ServiceProvider); - return; - } - - if (LuaImp?.GuiLibrary != null && LuaImp.GuiLibrary.HasLuaSurface) - { - LuaImp.GuiLibrary.DrawFinish(); - } - - var runningScripts = _luaList.Where(f => f.Enabled).ToList(); - - foreach (var file in runningScripts) - { - LuaImp.CallExitEvent(file.Thread); - - var functions = LuaImp.RegisteredFunctions.Where(lf => lf.Lua == file.Thread).ToList(); - - foreach (var function in functions) + if (LuaImp.IsRebootingCore == true) { - LuaImp.RegisteredFunctions.Remove(function); + // Even if the lua console is self-rebooting from client.reboot_core() we still want to re-inject dependencies + LuaImp.Restart(Emulator.ServiceProvider); + return; } - UpdateRegisteredFunctionsDialog(); + if (LuaImp.GuiLibrary != null && LuaImp.GuiLibrary.HasLuaSurface) + { + LuaImp.GuiLibrary.DrawFinish(); + } - file.Stop(); + runningScripts = LuaImp.RunningScripts.ToList(); + + foreach (var file in runningScripts) + { + LuaImp.CallExitEvent(file.Thread); + + var functions = LuaImp.RegisteredFunctions + .Where(lf => lf.Lua == file.Thread) + .ToList(); + + foreach (var function in functions) + { + LuaImp.RegisteredFunctions.Remove(function); + } + + UpdateRegisteredFunctionsDialog(); + + file.Stop(); + } } + var currentScripts = LuaImp?.ScriptList; // Temp fix for now LuaImp = new EmuLuaLibrary(Emulator.ServiceProvider); + if (currentScripts != null) + { + LuaImp.ScriptList.AddRange(currentScripts); + } + InputBox.AutoCompleteCustomSource.AddRange(LuaImp.Docs.Select(a => a.Library + "." + a.Name).ToArray()); foreach (var file in runningScripts) @@ -202,7 +210,7 @@ namespace BizHawk.Client.EmuHawk private void AddFileWatches() { _watches.Clear(); - foreach (var item in _luaList) + foreach (var item in LuaImp.ScriptList) { var processedPath = PathManager.TryMakeRelative(item.Path); string pathToLoad = ProcessPath(processedPath); @@ -246,8 +254,8 @@ namespace BizHawk.Client.EmuHawk { var luaFile = new LuaFile("", processedPath); - _luaList.Add(luaFile); - LuaListView.ItemCount = _luaList.Count; + LuaImp.ScriptList.Add(luaFile); + LuaListView.ItemCount = LuaImp.ScriptList.Count; Global.Config.RecentLua.Add(processedPath); if (!Global.Config.DisableLuaScriptsOnLoad) @@ -281,7 +289,7 @@ namespace BizHawk.Client.EmuHawk } else { - foreach (var file in _luaList.Where(file => processedPath == file.Path && file.Enabled == false && !Global.Config.DisableLuaScriptsOnLoad)) + foreach (var file in LuaImp.ScriptList.Where(file => processedPath == file.Path && file.Enabled == false && !Global.Config.DisableLuaScriptsOnLoad)) { file.Toggle(); break; @@ -295,7 +303,7 @@ namespace BizHawk.Client.EmuHawk private void UpdateDialog() { - LuaListView.ItemCount = _luaList.Count; + LuaListView.ItemCount = LuaImp.ScriptList.Count; LuaListView.Refresh(); UpdateNumberOfScripts(); UpdateRegisteredFunctionsDialog(); @@ -303,7 +311,7 @@ namespace BizHawk.Client.EmuHawk private void RunLuaScripts() { - foreach (var file in _luaList) + foreach (var file in LuaImp.ScriptList) { if (!file.Enabled && file.Thread == null) { @@ -334,8 +342,8 @@ namespace BizHawk.Client.EmuHawk private void SessionChangedCallback() { OutputMessages.Text = - (_luaList.Changes ? "* " : "") + - Path.GetFileName(_luaList.Filename); + (LuaImp.ScriptList.Changes ? "* " : "") + + Path.GetFileName(LuaImp.ScriptList.Filename); } private void LuaListView_QueryItemImage(int item, int subItem, out int imageIndex) @@ -346,11 +354,11 @@ namespace BizHawk.Client.EmuHawk return; } - if (_luaList[item].Paused) + if (LuaImp.ScriptList[item].Paused) { imageIndex = 2; } - else if (_luaList[item].Enabled) + else if (LuaImp.ScriptList[item].Enabled) { imageIndex = 1; } @@ -369,15 +377,15 @@ namespace BizHawk.Client.EmuHawk { if (column == 0) { - if (_luaList[index].IsSeparator) + if (LuaImp.ScriptList[index].IsSeparator) { color = BackColor; } - else if (_luaList[index].Enabled && !_luaList[index].Paused) + else if (LuaImp.ScriptList[index].Enabled && !LuaImp.ScriptList[index].Paused) { color = Color.LightCyan; } - else if (_luaList[index].Enabled && _luaList[index].Paused) + else if (LuaImp.ScriptList[index].Enabled && LuaImp.ScriptList[index].Paused) { color = Color.LightPink; } @@ -391,11 +399,11 @@ namespace BizHawk.Client.EmuHawk text = ""; if (column == 0) { - text = Path.GetFileNameWithoutExtension(_luaList[index].Path); // TODO: how about allow the user to name scripts? + text = Path.GetFileNameWithoutExtension(LuaImp.ScriptList[index].Path); // TODO: how about allow the user to name scripts? } else if (column == 1) { - text = DressUpRelative(_luaList[index].Path); + text = DressUpRelative(LuaImp.ScriptList[index].Path); } } @@ -436,8 +444,8 @@ namespace BizHawk.Client.EmuHawk { var message = ""; var total = SelectedFiles.Count(); - var active = _luaList.Count(file => file.Enabled); - var paused = _luaList.Count(file => file.Enabled && file.Paused); + var active = LuaImp.ScriptList.Count(file => file.Enabled); + var paused = LuaImp.ScriptList.Count(file => file.Enabled && file.Paused); if (total == 1) { @@ -462,7 +470,7 @@ namespace BizHawk.Client.EmuHawk private bool LuaAlreadyInSession(string path) { - return _luaList.Any(t => path == t.Path); + return LuaImp.ScriptList.Any(t => path == t.Path); } public void WriteToOutputWindow(string message) @@ -496,11 +504,11 @@ namespace BizHawk.Client.EmuHawk public bool LoadLuaSession(string path) { - var result = _luaList.LoadLuaSession(path); + var result = LuaImp.ScriptList.LoadLuaSession(path); RunLuaScripts(); UpdateDialog(); - _luaList.Changes = false; + LuaImp.ScriptList.Changes = false; return result; } @@ -511,7 +519,7 @@ namespace BizHawk.Client.EmuHawk /// should frame waiters be waken up? only use this immediately before a frame of emulation public void ResumeScripts(bool includeFrameWaiters) { - if (!_luaList.Any()) + if (!LuaImp.ScriptList.Any()) { return; } @@ -521,7 +529,7 @@ namespace BizHawk.Client.EmuHawk LuaImp.GuiLibrary.DrawNew("emu"); } - foreach (var lf in _luaList.Where(l => l.Enabled && l.Thread != null && !l.Paused)) + foreach (var lf in LuaImp.ScriptList.Where(l => l.Enabled && l.Thread != null && !l.Paused)) { try { @@ -552,22 +560,6 @@ namespace BizHawk.Client.EmuHawk } } - public void StartLuaDrawing() - { - if (_luaList.Any() && LuaImp.GuiLibrary.SurfaceIsNull) - { - LuaImp.GuiLibrary.DrawNew("emu"); - } - } - - public void EndLuaDrawing() - { - if (_luaList.Any()) - { - LuaImp.GuiLibrary.DrawFinish(); - } - } - public bool WaitOne(int timeout) { if (!IsHandleCreated || IsDisposed) @@ -581,10 +573,10 @@ namespace BizHawk.Client.EmuHawk private FileInfo GetSaveFileFromUser() { var sfd = new SaveFileDialog(); - if (!string.IsNullOrWhiteSpace(_luaList.Filename)) + if (!string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename)) { - sfd.FileName = Path.GetFileNameWithoutExtension(_luaList.Filename); - sfd.InitialDirectory = Path.GetDirectoryName(_luaList.Filename); + sfd.FileName = Path.GetFileNameWithoutExtension(LuaImp.ScriptList.Filename); + sfd.InitialDirectory = Path.GetDirectoryName(LuaImp.ScriptList.Filename); } else if (Global.Game != null) { @@ -613,22 +605,22 @@ namespace BizHawk.Client.EmuHawk var file = GetSaveFileFromUser(); if (file != null) { - _luaList.SaveSession(file.FullName); - OutputMessages.Text = Path.GetFileName(_luaList.Filename) + " saved."; + LuaImp.ScriptList.SaveSession(file.FullName); + OutputMessages.Text = Path.GetFileName(LuaImp.ScriptList.Filename) + " saved."; } } private void LoadSessionFromRecent(string path) { var doload = true; - if (_luaList.Changes) + if (LuaImp.ScriptList.Changes) { doload = AskSaveChanges(); } if (doload) { - if (!_luaList.LoadLuaSession(path)) + if (!LuaImp.ScriptList.LoadLuaSession(path)) { Global.Config.RecentLuaSession.HandleLoadError(path); } @@ -636,7 +628,7 @@ namespace BizHawk.Client.EmuHawk { RunLuaScripts(); UpdateDialog(); - _luaList.Changes = false; + LuaImp.ScriptList.Changes = false; } } @@ -645,16 +637,16 @@ namespace BizHawk.Client.EmuHawk public bool AskSaveChanges() { - if (_luaList.Changes && !string.IsNullOrEmpty(_luaList.Filename)) + if (LuaImp.ScriptList.Changes && !string.IsNullOrEmpty(LuaImp.ScriptList.Filename)) { GlobalWin.Sound.StopSound(); var result = MessageBox.Show("Save changes to session?", "Lua Console", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3); GlobalWin.Sound.StartSound(); if (result == DialogResult.Yes) { - if (!string.IsNullOrWhiteSpace(_luaList.Filename)) + if (!string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename)) { - _luaList.SaveSession(); + LuaImp.ScriptList.SaveSession(); } else { @@ -666,7 +658,7 @@ namespace BizHawk.Client.EmuHawk if (result == DialogResult.No) { - _luaList.Changes = false; + LuaImp.ScriptList.Changes = false; return true; } @@ -693,7 +685,7 @@ namespace BizHawk.Client.EmuHawk private void FileSubMenu_DropDownOpened(object sender, EventArgs e) { - SaveSessionMenuItem.Enabled = _luaList.Changes; + SaveSessionMenuItem.Enabled = LuaImp.ScriptList.Changes; } private void RecentSessionsSubMenu_DropDownOpened(object sender, EventArgs e) @@ -712,11 +704,11 @@ namespace BizHawk.Client.EmuHawk private void NewSessionMenuItem_Click(object sender, EventArgs e) { - var result = !_luaList.Changes || AskSaveChanges(); + var result = !LuaImp.ScriptList.Changes || AskSaveChanges(); if (result) { - _luaList.Clear(); + LuaImp.ScriptList.Clear(); ClearOutputWindow(); UpdateDialog(); } @@ -727,27 +719,27 @@ namespace BizHawk.Client.EmuHawk var file = GetFileFromUser("Lua Session Files (*.luases)|*.luases|All Files|*.*"); if (file != null) { - _luaList.LoadLuaSession(file.FullName); + LuaImp.ScriptList.LoadLuaSession(file.FullName); RunLuaScripts(); UpdateDialog(); - _luaList.Changes = false; + LuaImp.ScriptList.Changes = false; } } private void SaveSessionMenuItem_Click(object sender, EventArgs e) { - if (_luaList.Changes) + if (LuaImp.ScriptList.Changes) { - if (!string.IsNullOrWhiteSpace(_luaList.Filename)) + if (!string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename)) { - _luaList.SaveSession(); + LuaImp.ScriptList.SaveSession(); } else { SaveSessionAs(); } - OutputMessages.Text = Path.GetFileName(_luaList.Filename) + " saved."; + OutputMessages.Text = Path.GetFileName(LuaImp.ScriptList.Filename) + " saved."; } } @@ -778,21 +770,21 @@ namespace BizHawk.Client.EmuHawk MoveDownMenuItem.Enabled = LuaListView.SelectedIndices().Any(); - SelectAllMenuItem.Enabled = _luaList.Any(); - StopAllScriptsMenuItem.Enabled = _luaList.Any(script => script.Enabled); - RegisteredFunctionsMenuItem.Enabled = GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.Any(); + SelectAllMenuItem.Enabled = LuaImp.ScriptList.Any(); + StopAllScriptsMenuItem.Enabled = LuaImp.ScriptList.Any(script => script.Enabled); + RegisteredFunctionsMenuItem.Enabled = LuaImp.RegisteredFunctions.Any(); } private void NewScriptMenuItem_Click(object sender, EventArgs e) { var sfd = new SaveFileDialog { - InitialDirectory = !string.IsNullOrWhiteSpace(_luaList.Filename) ? - Path.GetDirectoryName(_luaList.Filename) : + InitialDirectory = !string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename) ? + Path.GetDirectoryName(LuaImp.ScriptList.Filename) : PathManager.MakeAbsolutePath(Global.Config.PathEntries.LuaPathFragment, null), DefaultExt = ".lua", - FileName = !string.IsNullOrWhiteSpace(_luaList.Filename) ? - Path.GetFileNameWithoutExtension(_luaList.Filename) : + FileName = !string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename) ? + Path.GetFileNameWithoutExtension(LuaImp.ScriptList.Filename) : Path.GetFileNameWithoutExtension(Global.Game.Name), OverwritePrompt = true, Filter = "Lua Scripts (*.lua)|*.lua|All Files (*.*)|*.*" @@ -804,7 +796,7 @@ namespace BizHawk.Client.EmuHawk { string defaultTemplate = "while true do\n\temu.frameadvance();\nend"; File.WriteAllText(sfd.FileName, defaultTemplate); - _luaList.Add(new LuaFile(Path.GetFileNameWithoutExtension(sfd.FileName), sfd.FileName)); + LuaImp.ScriptList.Add(new LuaFile(Path.GetFileNameWithoutExtension(sfd.FileName), sfd.FileName)); UpdateDialog(); System.Diagnostics.Process.Start(sfd.FileName); } @@ -822,7 +814,7 @@ namespace BizHawk.Client.EmuHawk private void ToggleScriptMenuItem_Click(object sender, EventArgs e) { - var files = !SelectedFiles.Any() && Global.Config.ToggleAllIfNoneSelected ? _luaList : SelectedFiles; + var files = !SelectedFiles.Any() && Global.Config.ToggleAllIfNoneSelected ? LuaImp.ScriptList : SelectedFiles; foreach (var item in files) { item.Toggle(); @@ -848,8 +840,8 @@ namespace BizHawk.Client.EmuHawk // We want any gui.text messages from a script to immediately update even when paused GlobalWin.OSD.ClearGUIText(); GlobalWin.Tools.UpdateToolsAfter(); - EndLuaDrawing(); - StartLuaDrawing(); + LuaImp.EndLuaDrawing(); + LuaImp.StartLuaDrawing(); } catch (IOException) { @@ -881,7 +873,7 @@ namespace BizHawk.Client.EmuHawk item.Stop(); if (Global.Config.RemoveRegisteredFunctionsOnToggle) { - GlobalWin.Tools.LuaConsole.LuaImp.RegisteredFunctions.ClearAll(); + LuaImp.RegisteredFunctions.ClearAll(); } } } @@ -927,7 +919,7 @@ namespace BizHawk.Client.EmuHawk LuaImp.RegisteredFunctions.Remove(function); } - _luaList.Remove(item); + LuaImp.ScriptList.Remove(item); } UpdateRegisteredFunctionsDialog(); @@ -954,7 +946,7 @@ namespace BizHawk.Client.EmuHawk { string text = File.ReadAllText(script.Path); File.WriteAllText(sfd.FileName, text); - _luaList.Add(new LuaFile(Path.GetFileNameWithoutExtension(sfd.FileName), sfd.FileName)); + LuaImp.ScriptList.Add(new LuaFile(Path.GetFileNameWithoutExtension(sfd.FileName), sfd.FileName)); UpdateDialog(); System.Diagnostics.Process.Start(sfd.FileName); } @@ -964,13 +956,13 @@ namespace BizHawk.Client.EmuHawk private void InsertSeparatorMenuItem_Click(object sender, EventArgs e) { var indices = LuaListView.SelectedIndices().ToList(); - if (indices.Any() && indices.Last() < _luaList.Count) + if (indices.Any() && indices.Last() < LuaImp.ScriptList.Count) { - _luaList.Insert(indices.Last(), LuaFile.SeparatorInstance); + LuaImp.ScriptList.Insert(indices.Last(), LuaFile.SeparatorInstance); } else { - _luaList.Add(LuaFile.SeparatorInstance); + LuaImp.ScriptList.Add(LuaFile.SeparatorInstance); } UpdateDialog(); @@ -986,9 +978,9 @@ namespace BizHawk.Client.EmuHawk foreach (var index in indices) { - var file = _luaList[index]; - _luaList.Remove(file); - _luaList.Insert(index - 1, file); + var file = LuaImp.ScriptList[index]; + LuaImp.ScriptList.Remove(file); + LuaImp.ScriptList.Insert(index - 1, file); } var newindices = indices.Select(t => t - 1).ToList(); @@ -1005,16 +997,16 @@ namespace BizHawk.Client.EmuHawk private void MoveDownMenuItem_Click(object sender, EventArgs e) { var indices = LuaListView.SelectedIndices().ToList(); - if (indices.Count == 0 || indices.Last() == _luaList.Count - 1) + if (indices.Count == 0 || indices.Last() == LuaImp.ScriptList.Count - 1) { return; } for (var i = indices.Count - 1; i >= 0; i--) { - var file = _luaList[indices[i]]; - _luaList.Remove(file); - _luaList.Insert(indices[i] + 1, file); + var file = LuaImp.ScriptList[indices[i]]; + LuaImp.ScriptList.Remove(file); + LuaImp.ScriptList.Insert(indices[i] + 1, file); } var newindices = indices.Select(t => t + 1).ToList(); @@ -1035,7 +1027,7 @@ namespace BizHawk.Client.EmuHawk private void StopAllScriptsMenuItem_Click(object sender, EventArgs e) { - _luaList.StopAllScripts(); + LuaImp.ScriptList.StopAllScripts(); } private void RegisteredFunctionsMenuItem_Click(object sender, EventArgs e) @@ -1192,7 +1184,7 @@ namespace BizHawk.Client.EmuHawk StopAllScriptsContextItem.Visible = ScriptContextSeparator.Visible = - _luaList.Any(file => file.Enabled); + LuaImp.ScriptList.Any(file => file.Enabled); } private void ConsoleContextMenu_Opening(object sender, CancelEventArgs e) @@ -1223,10 +1215,10 @@ namespace BizHawk.Client.EmuHawk } else if (Path.GetExtension(path).ToLower() == ".luases") { - _luaList.LoadLuaSession(path); + LuaImp.ScriptList.LoadLuaSession(path); RunLuaScripts(); UpdateDialog(); - _luaList.Changes = false; + LuaImp.ScriptList.Changes = false; return; } } @@ -1280,12 +1272,12 @@ namespace BizHawk.Client.EmuHawk // For getting the name of the .lua file, for some reason this field is kept blank in LuaFile.cs? // The Name variable gets emptied again near the end just in case it would break something. - for (var i = 0; i < _luaList.Count; i++) + for (var i = 0; i < LuaImp.ScriptList.Count; i++) { - var words = Regex.Split(_luaList[i].Path, ".lua"); + var words = Regex.Split(LuaImp.ScriptList[i].Path, ".lua"); var split = words[0].Split(Path.DirectorySeparatorChar); - luaListTemp.Add(_luaList[i]); + luaListTemp.Add(LuaImp.ScriptList[i]); luaListTemp[i].Name = split[split.Length - 1]; } @@ -1304,10 +1296,10 @@ namespace BizHawk.Client.EmuHawk break; } - for (var i = 0; i < _luaList.Count; i++) + for (var i = 0; i < LuaImp.ScriptList.Count; i++) { - _luaList[i] = luaListTemp[i]; - _luaList[i].Name = ""; + LuaImp.ScriptList[i] = luaListTemp[i]; + LuaImp.ScriptList[i].Name = ""; } UpdateDialog(); diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaDropDown.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaDropDown.cs index dbff0d558a..d74f41429f 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaDropDown.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaDropDown.cs @@ -7,14 +7,14 @@ namespace BizHawk.Client.EmuHawk public class LuaDropDown : ComboBox { public LuaDropDown(List items) - : base() { Items.AddRange(items.Cast().ToArray()); SelectedIndex = 0; DropDownStyle = ComboBoxStyle.DropDownList; } - public void SetItems(List items) { + public void SetItems(List items) + { Items.Clear(); Items.AddRange(items.Cast().ToArray()); SelectedIndex = 0; diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs index 727f73a231..96e03a5d60 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaFunctionsForm.cs @@ -41,8 +41,8 @@ namespace BizHawk.Client.EmuHawk private void LuaFunctionList_Load(object sender, EventArgs e) { FunctionList = GlobalWin.Tools.LuaConsole.LuaImp.Docs - .OrderBy(x => x.Library) - .ThenBy(x => x.Name) + .OrderBy(l => l.Library) + .ThenBy(l => l.Name) .ToList(); UpdateList(); FilterBox.Focus(); @@ -52,7 +52,6 @@ namespace BizHawk.Client.EmuHawk private void FunctionView_QueryItemBkColor(int index, int column, ref Color color) { - } private void FunctionView_QueryItemText(int index, int column, out string text) @@ -148,7 +147,7 @@ namespace BizHawk.Client.EmuHawk OrderColumn(e.Column); } - public class Sorting + private class Sorting { private bool _desc; private int _column = 1; diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs index d65745fe8b..2a53a725e9 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaRegisteredFunctionsList.cs @@ -7,7 +7,7 @@ namespace BizHawk.Client.EmuHawk { public partial class LuaRegisteredFunctionsList : Form { - public Point StartLocation = new Point(0, 0); + public Point StartLocation { get; set; } = new Point(0, 0); public LuaRegisteredFunctionsList() { InitializeComponent(); diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaTextBox.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaTextBox.cs index a194a42ba5..de4f33fdc8 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaTextBox.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaTextBox.cs @@ -1,28 +1,25 @@ -using System; -using System.Globalization; +using System.Globalization; using System.Windows.Forms; using BizHawk.Common.StringExtensions; -using BizHawk.Client.Common; namespace BizHawk.Client.EmuHawk { - enum BoxType { All, Signed, Unsigned, Hex }; - class LuaTextBox : TextBox + internal enum BoxType + { + All, Signed, Unsigned, Hex + } + + internal class LuaTextBox : TextBox { private BoxType _boxType = BoxType.All; public void SetType(BoxType type) { _boxType = type; - if (type != BoxType.All) - { - CharacterCasing = CharacterCasing.Upper; - } - else - { - CharacterCasing = CharacterCasing.Normal; - } + CharacterCasing = type != BoxType.All + ? CharacterCasing.Upper + : CharacterCasing.Normal; } protected override void OnKeyPress(KeyPressEventArgs e) @@ -33,7 +30,6 @@ namespace BizHawk.Client.EmuHawk protected override void OnKeyDown(KeyEventArgs e) { - if (e.KeyCode == Keys.Up) { switch (_boxType) @@ -76,7 +72,7 @@ namespace BizHawk.Client.EmuHawk private void Increment() { - string text = String.IsNullOrWhiteSpace(Text) ? "0" : Text; + string text = string.IsNullOrWhiteSpace(Text) ? "0" : Text; switch (_boxType) { case BoxType.Hex: @@ -90,6 +86,7 @@ namespace BizHawk.Client.EmuHawk { Text = "0"; } + break; case BoxType.Signed: var sval = int.Parse(text); @@ -102,6 +99,7 @@ namespace BizHawk.Client.EmuHawk { Text = "0"; } + break; case BoxType.Unsigned: var uval = uint.Parse(text); @@ -114,13 +112,14 @@ namespace BizHawk.Client.EmuHawk { Text = "0"; } + break; } } private void Decrement() { - string text = String.IsNullOrWhiteSpace(Text) ? "0" : Text; + string text = string.IsNullOrWhiteSpace(Text) ? "0" : Text; switch (_boxType) { case BoxType.Hex: @@ -130,6 +129,7 @@ namespace BizHawk.Client.EmuHawk hval--; Text = hval.ToString("X"); } + break; case BoxType.Signed: var sval = int.Parse(text); @@ -143,27 +143,40 @@ namespace BizHawk.Client.EmuHawk uval--; Text = uval.ToString(); } + break; } } private void SpecificValueBox_KeyPress(object sender, KeyPressEventArgs e) { - if (e.KeyChar == '\b') return; + if (e.KeyChar == '\b') + { + return; + } switch (_boxType) { case BoxType.Unsigned: if (!e.KeyChar.IsUnsigned()) + { e.Handled = true; + } + break; case BoxType.Signed: if (!e.KeyChar.IsSigned()) + { e.Handled = true; + } + break; case BoxType.Hex: if (!e.KeyChar.IsHex()) + { e.Handled = true; + } + break; } } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs b/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs index 38b3b54d04..23e1bb76ec 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/LuaWinform.cs @@ -1,47 +1,47 @@ using System; using System.Collections.Generic; using System.Windows.Forms; -using BizHawk.Client.Common; + using LuaInterface; +using BizHawk.Client.Common; + namespace BizHawk.Client.EmuHawk { public partial class LuaWinform : Form { - public List ControlEvents = new List(); + public List ControlEvents { get; } = new List(); - private string CurrentDirectory = Environment.CurrentDirectory; - - Lua OwnerThread; + private readonly string _currentDirectory = Environment.CurrentDirectory; + private readonly Lua _ownerThread; public LuaWinform(Lua ownerThread) { InitializeComponent(); - OwnerThread = ownerThread; + _ownerThread = ownerThread; StartPosition = FormStartPosition.CenterParent; Closing += (o, e) => CloseThis(); } private void LuaWinform_Load(object sender, EventArgs e) { - } - public void CloseThis() + private void CloseThis() { GlobalWin.Tools.LuaConsole.LuaImp.WindowClosed(Handle); } public void DoLuaEvent(IntPtr handle) { - LuaSandbox.Sandbox(OwnerThread, () => + LuaSandbox.Sandbox(_ownerThread, () => { - Environment.CurrentDirectory = CurrentDirectory; - foreach (LuaEvent l_event in ControlEvents) + Environment.CurrentDirectory = _currentDirectory; + foreach (LuaEvent luaEvent in ControlEvents) { - if (l_event.Control == handle) + if (luaEvent.Control == handle) { - l_event.Event.Call(); + luaEvent.Event.Call(); } } }); @@ -49,15 +49,14 @@ namespace BizHawk.Client.EmuHawk public class LuaEvent { - public LuaFunction Event; - public IntPtr Control; - - public LuaEvent() { } public LuaEvent(IntPtr handle, LuaFunction lfunction) { Event = lfunction; Control = handle; } + + public LuaFunction Event { get; } + public IntPtr Control { get; } } } } diff --git a/BizHawk.Client.EmuHawk/tools/Lua/SyncTextBox.cs b/BizHawk.Client.EmuHawk/tools/Lua/SyncTextBox.cs index 8773922bc4..8359c1109c 100644 --- a/BizHawk.Client.EmuHawk/tools/Lua/SyncTextBox.cs +++ b/BizHawk.Client.EmuHawk/tools/Lua/SyncTextBox.cs @@ -2,20 +2,21 @@ using System.Windows.Forms; using System.Runtime.InteropServices; -class SyncTextBox : RichTextBox +internal class SyncTextBox : RichTextBox { public SyncTextBox() { this.Multiline = true; this.ScrollBars = RichTextBoxScrollBars.Vertical; - } + public Control Buddy { get; set; } private static bool scrolling; // In case buddy tries to scroll us protected override void WndProc(ref Message m) { base.WndProc(ref m); + // Trap WM_VSCROLL message and pass to buddy if ((m.Msg == 0x115 || m.Msg == 0x20a) && !scrolling && Buddy != null && Buddy.IsHandleCreated) { @@ -24,6 +25,7 @@ class SyncTextBox : RichTextBox scrolling = false; } } + [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); } \ No newline at end of file diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.Designer.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.Designer.cs index 38b9e3b306..bacdef1f33 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.Designer.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.Designer.cs @@ -150,7 +150,7 @@ // this.BranchView.AllowColumnReorder = false; this.BranchView.AllowColumnResize = false; - this.BranchView.allowRightClickSelecton = true; + this.BranchView.AllowRightClickSelecton = true; this.BranchView.AlwaysScroll = false; this.BranchView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) @@ -161,7 +161,7 @@ this.BranchView.HideWasLagFrames = false; this.BranchView.HorizontalOrientation = false; this.BranchView.LagFramesToHide = 0; - this.BranchView.letKeysModifySelection = false; + this.BranchView.LetKeysModifySelection = false; this.BranchView.Location = new System.Drawing.Point(6, 19); this.BranchView.MaxCharactersInHorizontal = 1; this.BranchView.MultiSelect = false; @@ -170,7 +170,7 @@ this.BranchView.ScrollSpeed = 13; this.BranchView.SeekingCutoffInterval = 0; this.BranchView.Size = new System.Drawing.Size(186, 224); - this.BranchView.suspendHotkeys = false; + this.BranchView.SuspendHotkeys = false; this.BranchView.TabIndex = 0; this.BranchView.PointedCellChanged += new BizHawk.Client.EmuHawk.InputRoll.CellChangeEventHandler(this.BranchView_PointedCellChanged); this.BranchView.CellDropped += new BizHawk.Client.EmuHawk.InputRoll.CellDroppedEvent(this.BranchView_CellDropped); diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs index 41edaaf128..e3df562925 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/BookmarksBranchesBox.cs @@ -2,32 +2,36 @@ using System.Collections.Generic; using System.ComponentModel; using System.Drawing; -using System.Data; using System.Linq; -using System.Text; using System.Windows.Forms; -using System.Windows.Media; -using BizHawk.Emulation.Common; + using BizHawk.Client.Common; -using BizHawk.Common; using BizHawk.Client.EmuHawk.WinFormExtensions; namespace BizHawk.Client.EmuHawk { public partial class BookmarksBranchesBox : UserControl { - public TAStudio Tastudio { get; set; } private const string BranchNumberColumnName = "BranchNumberColumn"; private const string FrameColumnName = "FrameColumn"; private const string UserTextColumnName = "TextColumn"; - private readonly PlatformFrameRates FrameRates = new PlatformFrameRates(); - private ScreenshotForm Screenshot = new ScreenshotForm(); - private TasMovie Movie { get { return Tastudio.CurrentTasMovie; } } - public TasBranch BackupBranch; - private enum BranchUndo { Load, Update, Text, Remove, None } + + private readonly ScreenshotForm Screenshot = new ScreenshotForm(); + + private TasMovie Movie => Tastudio.CurrentTasMovie; + private TasBranch _backupBranch; private BranchUndo _branchUndo = BranchUndo.None; private int LongestBranchText = 0; - public int HoverInterval { + + private enum BranchUndo + { + Load, Update, Text, Remove, None + } + + public TAStudio Tastudio { get; set; } + + public int HoverInterval + { get { return BranchView.HoverInterval; } set { BranchView.HoverInterval = value; } } @@ -36,7 +40,7 @@ namespace BizHawk.Client.EmuHawk { InitializeComponent(); - BranchView.AllColumns.AddRange(new InputRoll.RollColumn[] + BranchView.AllColumns.AddRange(new[] { new InputRoll.RollColumn { @@ -82,7 +86,6 @@ namespace BizHawk.Client.EmuHawk text = GetBranch(index).Frame.ToString(); break; case UserTextColumnName: - //text = GetBranch(index).TimeStamp.ToString(@"hh\:mm\:ss\.ff"); text = GetBranch(index).UserText; break; } @@ -95,17 +98,14 @@ namespace BizHawk.Client.EmuHawk { var record = Tastudio.CurrentTasMovie[branch.Frame]; if (index == Movie.CurrentBranch) - color = TAStudio.CurrentFrame_InputLog; // SystemColors.HotTrack; + { + color = TAStudio.CurrentFrame_InputLog; + } else if (record.Lagged.HasValue) { - if (record.Lagged.Value) - { - color = TAStudio.LagZone_InputLog; - } - else - { - color = TAStudio.GreenZone_InputLog; - } + color = record.Lagged.Value + ? TAStudio.LagZone_InputLog + : TAStudio.GreenZone_InputLog; } } @@ -174,7 +174,6 @@ namespace BizHawk.Client.EmuHawk var stateInfo = new KeyValuePair(branch.Frame, branch.CoreData); Tastudio.LoadState(stateInfo); QuickBmpFile.Copy(new BitmapBufferVideoProvider(branch.OSDFrameBuffer), Tastudio.VideoProvider); - //GlobalWin.MainForm.PauseEmulator(); GlobalWin.MainForm.PauseOnFrame = null; Tastudio.RefreshDialog(); } @@ -190,8 +189,6 @@ namespace BizHawk.Client.EmuHawk if (SelectedBranch != null) { int index = BranchView.SelectedRows.First(); - //if (Movie.CurrentBranch == index) // if the current branch was edited, we should allow loading it. some day there might be a proper check - // return; Movie.CurrentBranch = index; LoadBranch(SelectedBranch); BranchView.Refresh(); @@ -224,11 +221,14 @@ namespace BizHawk.Client.EmuHawk private void LoadBranchToolStripMenuItem_Click(object sender, EventArgs e) { - BackupBranch = CreateBranch(); + _backupBranch = CreateBranch(); var currentHashes = Movie.Branches.Select(b => b.UniqueIdentifier.GetHashCode()).ToList(); - do BackupBranch.UniqueIdentifier = Guid.NewGuid(); - while (currentHashes.Contains(BackupBranch.UniqueIdentifier.GetHashCode())); + do + { + _backupBranch.UniqueIdentifier = Guid.NewGuid(); + } + while (currentHashes.Contains(_backupBranch.UniqueIdentifier.GetHashCode())); UndoBranchToolStripMenuItem.Enabled = UndoBranchButton.Enabled = true; UndoBranchToolStripMenuItem.Text = "Undo Branch Load"; @@ -244,14 +244,14 @@ namespace BizHawk.Client.EmuHawk { Movie.CurrentBranch = BranchView.SelectedRows.First(); - BackupBranch = SelectedBranch.Clone(); + _backupBranch = SelectedBranch.Clone(); UndoBranchToolStripMenuItem.Enabled = UndoBranchButton.Enabled = true; UndoBranchToolStripMenuItem.Text = "Undo Branch Update"; toolTip1.SetToolTip(UndoBranchButton, "Undo Branch Update"); _branchUndo = BranchUndo.Update; UpdateBranch(SelectedBranch); - GlobalWin.OSD.AddMessage("Saved branch " + Movie.CurrentBranch.ToString()); + GlobalWin.OSD.AddMessage("Saved branch " + Movie.CurrentBranch); } } @@ -264,8 +264,8 @@ namespace BizHawk.Client.EmuHawk if (EditBranchTextPopUp(index)) { - BackupBranch = SelectedBranch.Clone(); - BackupBranch.UserText = oldText; + _backupBranch = SelectedBranch.Clone(); + _backupBranch.UserText = oldText; UndoBranchToolStripMenuItem.Enabled = UndoBranchButton.Enabled = true; UndoBranchToolStripMenuItem.Text = "Undo Branch Text Edit"; toolTip1.SetToolTip(UndoBranchButton, "Undo Branch Text Edit"); @@ -300,7 +300,7 @@ namespace BizHawk.Client.EmuHawk Movie.CurrentBranch--; } - BackupBranch = SelectedBranch.Clone(); + _backupBranch = SelectedBranch.Clone(); UndoBranchToolStripMenuItem.Enabled = UndoBranchButton.Enabled = true; UndoBranchToolStripMenuItem.Text = "Undo Branch Removal"; toolTip1.SetToolTip(UndoBranchButton, "Undo Branch Removal"); @@ -315,7 +315,6 @@ namespace BizHawk.Client.EmuHawk BranchView.SelectRow(Movie.BranchCount - 1, true); } - //BranchView.Refresh(); Tastudio.RefreshDialog(); GlobalWin.OSD.AddMessage("Removed branch " + index.ToString()); } @@ -325,25 +324,26 @@ namespace BizHawk.Client.EmuHawk { if (_branchUndo == BranchUndo.Load) { - LoadBranch(BackupBranch); + LoadBranch(_backupBranch); GlobalWin.OSD.AddMessage("Branch Load canceled"); } else if (_branchUndo == BranchUndo.Update) { - Movie.UpdateBranch(Movie.GetBranch(BackupBranch.UniqueIdentifier), BackupBranch); + Movie.UpdateBranch(Movie.GetBranch(_backupBranch.UniqueIdentifier), _backupBranch); GlobalWin.OSD.AddMessage("Branch Update canceled"); } else if (_branchUndo == BranchUndo.Text) { - Movie.GetBranch(BackupBranch.UniqueIdentifier).UserText = BackupBranch.UserText; + Movie.GetBranch(_backupBranch.UniqueIdentifier).UserText = _backupBranch.UserText; GlobalWin.OSD.AddMessage("Branch Text Edit canceled"); } else if (_branchUndo == BranchUndo.Remove) { - Movie.AddBranch(BackupBranch); + Movie.AddBranch(_backupBranch); BranchView.RowCount = Movie.BranchCount; GlobalWin.OSD.AddMessage("Branch Removal canceled"); } + UndoBranchToolStripMenuItem.Enabled = UndoBranchButton.Enabled = false; BranchView.Refresh(); Tastudio.RefreshDialog(); @@ -359,7 +359,9 @@ namespace BizHawk.Client.EmuHawk public void LoadBranchExternal(int slot = -1) { if (Tastudio.FloatEditingMode) + { return; + } if (slot != -1) { @@ -373,13 +375,16 @@ namespace BizHawk.Client.EmuHawk return; } } + LoadBranchToolStripMenuItem_Click(null, null); } public void UpdateBranchExternal(int slot = -1) { if (Tastudio.FloatEditingMode) + { return; + } if (slot != -1) { @@ -393,6 +398,7 @@ namespace BizHawk.Client.EmuHawk return; } } + UpdateBranchToolStripMenuItem_Click(null, null); } @@ -404,7 +410,9 @@ namespace BizHawk.Client.EmuHawk public void SelectBranchExternal(int slot) { if (Tastudio.FloatEditingMode) + { return; + } if (GetBranch(slot) != null) { @@ -425,6 +433,7 @@ namespace BizHawk.Client.EmuHawk BranchView.Refresh(); return; } + int sel = BranchView.SelectedRows.First(); if (next) { @@ -442,14 +451,15 @@ namespace BizHawk.Client.EmuHawk BranchView.SelectRow(sel - 1, true); } } + BranchView.Refresh(); } public void NonExistentBranchMessage(int slot) { - string binding = Global.Config.HotkeyBindings.Where(x => x.DisplayName == "Add Branch").FirstOrDefault().Bindings; - GlobalWin.OSD.AddMessage("Branch " + slot.ToString() + " does not exist"); - GlobalWin.OSD.AddMessage("Use " + binding + " to add branches"); + string binding = Global.Config.HotkeyBindings.First(x => x.DisplayName == "Add Branch").Bindings; + GlobalWin.OSD.AddMessage($"Branch {slot} does not exist"); + GlobalWin.OSD.AddMessage($"Use {binding} to add branches"); } public void UpdateValues() @@ -471,18 +481,25 @@ namespace BizHawk.Client.EmuHawk foreach (TasBranch b in Movie.Branches) { if (string.IsNullOrEmpty(b.UserText)) + { continue; + } if (temp < b.UserText.Length) + { temp = b.UserText.Length; + } } + LongestBranchText = temp; - int textWidth = LongestBranchText * 12 + 14; // sorry for magic numbers. see TAStudio.SetUpColumns() - InputRoll.RollColumn column = BranchView.AllColumns.Where(c => c.Name == UserTextColumnName).SingleOrDefault(); + int textWidth = (LongestBranchText * 12) + 14; // sorry for magic numbers. see TAStudio.SetUpColumns() + var column = BranchView.AllColumns.Single(c => c.Name == UserTextColumnName); if (textWidth < 90) + { textWidth = 90; + } if (column.Width != textWidth) { @@ -495,9 +512,11 @@ namespace BizHawk.Client.EmuHawk { TasBranch branch = Movie.GetBranch(index); if (branch == null) + { return false; + } - InputPrompt i = new InputPrompt + var i = new InputPrompt { Text = "Text for branch " + index, TextInputType = InputPrompt.InputType.Text, @@ -516,6 +535,7 @@ namespace BizHawk.Client.EmuHawk UpdateValues(); return true; } + return false; } @@ -557,7 +577,7 @@ namespace BizHawk.Client.EmuHawk private void BranchView_MouseMove(object sender, MouseEventArgs e) { - if (BranchView.CurrentCell == null || !BranchView.CurrentCell.RowIndex.HasValue || BranchView.CurrentCell.Column == null) + if (BranchView.CurrentCell?.RowIndex == null || BranchView.CurrentCell.Column == null) { Screenshot.FadeOut(); } @@ -582,7 +602,7 @@ namespace BizHawk.Client.EmuHawk private void BranchView_PointedCellChanged(object sender, InputRoll.CellEventArgs e) { - if (e.NewCell != null && e.NewCell.RowIndex.HasValue && e.NewCell.Column != null && e.NewCell.RowIndex < Movie.BranchCount) + if (e.NewCell?.RowIndex != null && e.NewCell.Column != null && e.NewCell.RowIndex < Movie.BranchCount) { if (BranchView.CurrentCell.Column.Name == BranchNumberColumnName && BranchView.CurrentCell.RowIndex.HasValue && diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/DefaultGreenzoneSettings.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/DefaultGreenzoneSettings.cs index 96f8e5322f..513cbc5bcf 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/DefaultGreenzoneSettings.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/DefaultGreenzoneSettings.cs @@ -1,10 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Client.Common; @@ -13,32 +7,32 @@ namespace BizHawk.Client.EmuHawk { public partial class DefaultGreenzoneSettings : Form { - TasStateManagerSettings settings; + private TasStateManagerSettings _settings; public DefaultGreenzoneSettings() { InitializeComponent(); - settings = new TasStateManagerSettings(Global.Config.DefaultTasProjSettings); + _settings = new TasStateManagerSettings(Global.Config.DefaultTasProjSettings); - SettingsPropertyGrid.SelectedObject = settings; + SettingsPropertyGrid.SelectedObject = _settings; } private void OkBtn_Click(object sender, EventArgs e) { - Global.Config.DefaultTasProjSettings = settings; - this.Close(); + Global.Config.DefaultTasProjSettings = _settings; + Close(); } private void CancelBtn_Click(object sender, EventArgs e) { - this.Close(); + Close(); } private void DefaultsButton_Click(object sender, EventArgs e) { - settings = new TasStateManagerSettings(); - SettingsPropertyGrid.SelectedObject = settings; + _settings = new TasStateManagerSettings(); + SettingsPropertyGrid.SelectedObject = _settings; } } } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/FramesPrompt.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/FramesPrompt.cs index 0d646bbbad..6f8e6b12f0 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/FramesPrompt.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/FramesPrompt.cs @@ -1,10 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; using System.Windows.Forms; namespace BizHawk.Client.EmuHawk @@ -16,10 +10,7 @@ namespace BizHawk.Client.EmuHawk InitializeComponent(); } - public int Frames - { - get { return NumFramesBox.ToRawInt() ?? 0; } - } + public int Frames => NumFramesBox.ToRawInt() ?? 0; private void FramesPrompt_Load(object sender, EventArgs e) { diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/GreenzoneSettings.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/GreenzoneSettings.cs index a446d3474e..2c81c328fe 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/GreenzoneSettings.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/GreenzoneSettings.cs @@ -1,14 +1,7 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Emulation.Common; -using BizHawk.Emulation.Common.IEmulatorExtensions; using BizHawk.Client.Common; namespace BizHawk.Client.EmuHawk @@ -17,11 +10,12 @@ namespace BizHawk.Client.EmuHawk { public IStatable Statable { get; set; } - private readonly TasStateManagerSettings Settings; + private readonly TasStateManagerSettings _settings; private decimal _stateSizeMb; + public StateHistorySettingsForm(TasStateManagerSettings settings) { - Settings = settings; + _settings = settings; InitializeComponent(); } @@ -30,38 +24,38 @@ namespace BizHawk.Client.EmuHawk _stateSizeMb = Statable.SaveStateBinary().Length / (decimal)1024 / (decimal)1024; if (Environment.Is64BitProcess) // ? + { MemCapacityNumeric.Maximum = 1024 * 8; + } else + { MemCapacityNumeric.Maximum = 1024; + } - MemCapacityNumeric.Value = Settings.Capacitymb < MemCapacityNumeric.Maximum ? - Settings.Capacitymb : MemCapacityNumeric.Maximum; - DiskCapacityNumeric.Value = Settings.DiskCapacitymb < MemCapacityNumeric.Maximum ? - Settings.DiskCapacitymb : MemCapacityNumeric.Maximum; - SaveCapacityNumeric.Value = Settings.DiskSaveCapacitymb < MemCapacityNumeric.Maximum ? - Settings.DiskSaveCapacitymb : MemCapacityNumeric.Maximum; + MemCapacityNumeric.Value = _settings.Capacitymb < MemCapacityNumeric.Maximum ? + _settings.Capacitymb : MemCapacityNumeric.Maximum; + DiskCapacityNumeric.Value = _settings.DiskCapacitymb < MemCapacityNumeric.Maximum ? + _settings.DiskCapacitymb : MemCapacityNumeric.Maximum; + SaveCapacityNumeric.Value = _settings.DiskSaveCapacitymb < MemCapacityNumeric.Maximum ? + _settings.DiskSaveCapacitymb : MemCapacityNumeric.Maximum; - StateGap.Value = Settings.StateGap; + StateGap.Value = _settings.StateGap; SavestateSizeLabel.Text = Math.Round(_stateSizeMb, 2).ToString() + " mb"; CapacityNumeric_ValueChanged(null, null); SaveCapacityNumeric_ValueChanged(null, null); - BranchStatesInTasproj.Checked = Settings.BranchStatesInTasproj; - EraseBranchStatesFirst.Checked = Settings.EraseBranchStatesFirst; + BranchStatesInTasproj.Checked = _settings.BranchStatesInTasproj; + EraseBranchStatesFirst.Checked = _settings.EraseBranchStatesFirst; } - private int MaxStatesInCapacity - { - get { return (int)Math.Floor(MemCapacityNumeric.Value / _stateSizeMb) - + (int)Math.Floor(DiskCapacityNumeric.Value / _stateSizeMb); - } - } + private int MaxStatesInCapacity => (int)Math.Floor(MemCapacityNumeric.Value / _stateSizeMb) + + (int)Math.Floor(DiskCapacityNumeric.Value / _stateSizeMb); private void OkBtn_Click(object sender, EventArgs e) { - Settings.Capacitymb = (int)MemCapacityNumeric.Value; - Settings.DiskCapacitymb = (int)DiskCapacityNumeric.Value; - Settings.DiskSaveCapacitymb = (int)SaveCapacityNumeric.Value; - Settings.StateGap = (int)StateGap.Value; + _settings.Capacitymb = (int)MemCapacityNumeric.Value; + _settings.DiskCapacitymb = (int)DiskCapacityNumeric.Value; + _settings.DiskSaveCapacitymb = (int)SaveCapacityNumeric.Value; + _settings.StateGap = (int)StateGap.Value; DialogResult = DialogResult.OK; Close(); } @@ -86,17 +80,19 @@ namespace BizHawk.Client.EmuHawk private void BranchStatesInTasproj_CheckedChanged(object sender, EventArgs e) { - Settings.BranchStatesInTasproj = BranchStatesInTasproj.Checked; + _settings.BranchStatesInTasproj = BranchStatesInTasproj.Checked; } private void EraseBranchStatesFIrst_CheckedChanged(object sender, EventArgs e) { - Settings.EraseBranchStatesFirst = EraseBranchStatesFirst.Checked; + _settings.EraseBranchStatesFirst = EraseBranchStatesFirst.Checked; } private void StateGap_ValueChanged(object sender, EventArgs e) { - NumFramesLabel.Text = ((StateGap.Value == 0) ? "frame" : (1 << (int)StateGap.Value).ToString() + " frames"); + NumFramesLabel.Text = StateGap.Value == 0 + ? "frame" + : $"{1 << (int)StateGap.Value} frames"; } } } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/HeaderEditor.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/HeaderEditor.cs index 083985a1e7..9b2c622dc6 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/HeaderEditor.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/HeaderEditor.cs @@ -1,10 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Client.Common; @@ -13,36 +7,37 @@ namespace BizHawk.Client.EmuHawk { public partial class MovieHeaderEditor : Form { - private readonly IMovie Movie; + private readonly IMovie _movie; + public MovieHeaderEditor(IMovie movie) { - Movie = movie; + _movie = movie; InitializeComponent(); } private void MovieHeaderEditor_Load(object sender, EventArgs e) { - AuthorTextBox.Text = Movie.Author; - EmulatorVersionTextBox.Text = Movie.EmulatorVersion; - PlatformTextBox.Text = Movie.SystemID; - CoreTextBox.Text = Movie.Core; - BoardNameTextBox.Text = Movie.BoardName; - GameNameTextBox.Text = Movie.GameName; + AuthorTextBox.Text = _movie.Author; + EmulatorVersionTextBox.Text = _movie.EmulatorVersion; + PlatformTextBox.Text = _movie.SystemID; + CoreTextBox.Text = _movie.Core; + BoardNameTextBox.Text = _movie.BoardName; + GameNameTextBox.Text = _movie.GameName; } private void OkBtn_Click(object sender, EventArgs e) { - Movie.Author = AuthorTextBox.Text; + _movie.Author = AuthorTextBox.Text; if (MakeDefaultCheckbox.Checked) { Global.Config.DefaultAuthor = AuthorTextBox.Text; } - Movie.EmulatorVersion = EmulatorVersionTextBox.Text; - Movie.SystemID = PlatformTextBox.Text; - Movie.Core = CoreTextBox.Text; - Movie.BoardName = BoardNameTextBox.Text; - Movie.GameName = GameNameTextBox.Text; + _movie.EmulatorVersion = EmulatorVersionTextBox.Text; + _movie.SystemID = PlatformTextBox.Text; + _movie.Core = CoreTextBox.Text; + _movie.BoardName = BoardNameTextBox.Text; + _movie.GameName = GameNameTextBox.Text; DialogResult = DialogResult.OK; Close(); diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.Designer.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.Designer.cs index fdc4370861..fef9164076 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.Designer.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.Designer.cs @@ -185,7 +185,7 @@ // this.MarkerView.AllowColumnReorder = false; this.MarkerView.AllowColumnResize = false; - this.MarkerView.allowRightClickSelecton = true; + this.MarkerView.AllowRightClickSelecton = true; this.MarkerView.AlwaysScroll = false; this.MarkerView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.cs index b5e1f1eb8b..9646808d86 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/MarkerControl.cs @@ -2,13 +2,10 @@ using System.Collections.Generic; using System.ComponentModel; using System.Drawing; -using System.Data; using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Client.Common; -using BizHawk.Emulation.Common; using BizHawk.Client.EmuHawk.WinFormExtensions; namespace BizHawk.Client.EmuHawk @@ -16,13 +13,13 @@ namespace BizHawk.Client.EmuHawk public partial class MarkerControl : UserControl { public TAStudio Tastudio { get; set; } - public TasMovieMarkerList Markers { get { return Tastudio.CurrentTasMovie.Markers; } } + public TasMovieMarkerList Markers => Tastudio.CurrentTasMovie.Markers; public MarkerControl() { InitializeComponent(); - MarkerView.AllColumns.AddRange(new InputRoll.RollColumn[] + MarkerView.AllColumns.AddRange(new[] { new InputRoll.RollColumn { @@ -44,15 +41,14 @@ namespace BizHawk.Client.EmuHawk private void MarkerControl_Load(object sender, EventArgs e) { - } - public InputRoll MarkerInputRoll { get { return MarkerView; } } + public InputRoll MarkerInputRoll => MarkerView; private void MarkerView_QueryItemBkColor(int index, InputRoll.RollColumn column, ref Color color) { var prev = Markers.PreviousOrCurrent(Tastudio.Emulator.Frame); - + if (prev != null && index == Markers.IndexOf(prev)) { // feos: taseditor doesn't have it, so we're free to set arbitrary color scheme. and I prefer consistency @@ -80,7 +76,9 @@ namespace BizHawk.Client.EmuHawk } } else + { color = Color.White; + } } private void MarkerView_QueryItemText(int index, InputRoll.RollColumn column, out string text, ref int offsetX, ref int offsetY) @@ -165,7 +163,7 @@ namespace BizHawk.Client.EmuHawk if (editText) { - InputPrompt i = new InputPrompt + var i = new InputPrompt { Text = "Marker for frame " + markerFrame, TextInputType = InputPrompt.InputType.Text, @@ -191,6 +189,7 @@ namespace BizHawk.Client.EmuHawk Markers.Add(new TasMovieMarker(markerFrame, "")); UpdateValues(); } + Tastudio.RefreshDialog(); } @@ -198,15 +197,15 @@ namespace BizHawk.Client.EmuHawk { var markerFrame = marker.Frame; var point = default(Point); - InputPrompt i = new InputPrompt + var i = new InputPrompt { Text = "Marker for frame " + markerFrame, TextInputType = InputPrompt.InputType.Text, Message = "Enter a message", InitialValue = - Markers.IsMarker(markerFrame) ? - Markers.PreviousOrCurrent(markerFrame).Message : - "" + Markers.IsMarker(markerFrame) + ? Markers.PreviousOrCurrent(markerFrame).Message + : "" }; if (followCursor) @@ -214,6 +213,7 @@ namespace BizHawk.Client.EmuHawk point = Cursor.Position; point.Offset(i.Width / -2, i.Height / -2); } + var result = i.ShowHawkDialog(position: point); if (result == DialogResult.OK) @@ -225,10 +225,7 @@ namespace BizHawk.Client.EmuHawk public void UpdateValues() { - if (MarkerView != null && - Tastudio != null && - Tastudio.CurrentTasMovie != null && - Markers != null) + if (MarkerView != null && Tastudio?.CurrentTasMovie != null && Markers != null) { MarkerView.RowCount = Markers.Count; } @@ -270,8 +267,7 @@ namespace BizHawk.Client.EmuHawk // A much more useful feature would be to easily jump to it. private void MarkerView_MouseDoubleClick(object sender, MouseEventArgs e) { - if (MarkerView.CurrentCell != null && MarkerView.CurrentCell.RowIndex.HasValue && - MarkerView.CurrentCell.RowIndex < MarkerView.RowCount) + if (MarkerView.CurrentCell?.RowIndex != null && MarkerView.CurrentCell.RowIndex < MarkerView.RowCount) { var marker = Markers[MarkerView.CurrentCell.RowIndex.Value]; Tastudio.GoToFrame(marker.Frame); @@ -284,8 +280,10 @@ namespace BizHawk.Client.EmuHawk { var index = MarkerView.SelectedRows.First(); var marker = Markers[index]; + return marker.Frame; } + return -1; } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/PatternsForm.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/PatternsForm.cs index 975e18fe78..ea42894388 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/PatternsForm.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/PatternsForm.cs @@ -1,10 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Client.Common; @@ -13,17 +8,32 @@ namespace BizHawk.Client.EmuHawk { public partial class PatternsForm : Form { - private TAStudio tastudio; + private readonly TAStudio _tastudio; + + private readonly List _counts = new List(); + private readonly List _values = new List(); + private int _loopAt; + private bool _updating; + + private string SelectedButton => ButtonBox.Text; + + private bool IsBool => SelectedButton == "Default bool Auto-Fire" || Global.MovieSession.MovieControllerAdapter.Definition.BoolButtons.Contains(SelectedButton); public PatternsForm(TAStudio owner) { InitializeComponent(); - tastudio = owner; + _tastudio = owner; foreach (var button in Global.MovieSession.MovieControllerAdapter.Definition.BoolButtons) + { ButtonBox.Items.Add(button); + } + foreach (var button in Global.MovieSession.MovieControllerAdapter.Definition.FloatControls) + { ButtonBox.Items.Add(button); + } + ButtonBox.Items.Add("Default bool Auto-Fire"); ButtonBox.Items.Add("Default float Auto-Fire"); } @@ -33,18 +43,12 @@ namespace BizHawk.Client.EmuHawk ButtonBox.SelectedIndex = 0; } - List counts = new List(); - List values = new List(); - int loopAt; - string selectedButton { get { return ButtonBox.Text; } } - bool isBool { get { return selectedButton == "Default bool Auto-Fire" || Global.MovieSession.MovieControllerAdapter.Definition.BoolButtons.Contains(selectedButton); } } - private void ButtonBox_SelectedIndexChanged(object sender, EventArgs e) { GetPattern(); UpdateDisplay(); - if (isBool) + if (IsBool) { OnOffBox.Visible = true; ValueNum.Visible = false; @@ -54,22 +58,28 @@ namespace BizHawk.Client.EmuHawk ValueNum.Visible = true; OnOffBox.Visible = false; } - CountNum.Value = counts[0]; + + CountNum.Value = _counts[0]; } private void PatternList_SelectedIndexChanged(object sender, EventArgs e) { if (!_updating) + { UpdateDisplay(); + } } private void InsertButton_Click(object sender, EventArgs e) { - counts.Insert(PatternList.SelectedIndex, 1); + _counts.Insert(PatternList.SelectedIndex, 1); string defaultStr = "false"; - if (!isBool) + if (!IsBool) + { defaultStr = "0"; - values.Insert(PatternList.SelectedIndex, defaultStr); + } + + _values.Insert(PatternList.SelectedIndex, defaultStr); UpdatePattern(); UpdateDisplay(); @@ -77,8 +87,8 @@ namespace BizHawk.Client.EmuHawk private void DeleteButton_Click(object sender, EventArgs e) { - counts.RemoveAt(PatternList.SelectedIndex); - values.RemoveAt(PatternList.SelectedIndex); + _counts.RemoveAt(PatternList.SelectedIndex); + _values.RemoveAt(PatternList.SelectedIndex); UpdatePattern(); UpdateDisplay(); } @@ -90,36 +100,48 @@ namespace BizHawk.Client.EmuHawk private void ValueNum_ValueChanged(object sender, EventArgs e) { - if (_updating || PatternList.SelectedIndex == -1 || PatternList.SelectedIndex >= counts.Count) + if (_updating || PatternList.SelectedIndex == -1 || PatternList.SelectedIndex >= _counts.Count) + { return; + } - values[PatternList.SelectedIndex] = ValueNum.Value.ToString(); + _values[PatternList.SelectedIndex] = ValueNum.Value.ToString(); UpdatePattern(); UpdateDisplay(); } + private void OnOffBox_CheckedChanged(object sender, EventArgs e) { - if (_updating || PatternList.SelectedIndex == -1 || PatternList.SelectedIndex >= counts.Count) + if (_updating || PatternList.SelectedIndex == -1 || PatternList.SelectedIndex >= _counts.Count) + { return; + } - values[PatternList.SelectedIndex] = OnOffBox.Checked.ToString(); + _values[PatternList.SelectedIndex] = OnOffBox.Checked.ToString(); UpdatePattern(); UpdateDisplay(); } + private void CountNum_ValueChanged(object sender, EventArgs e) { - if (_updating || PatternList.SelectedIndex == -1 || PatternList.SelectedIndex > counts.Count) + if (_updating || PatternList.SelectedIndex == -1 || PatternList.SelectedIndex > _counts.Count) + { return; + } - if (PatternList.SelectedIndex == counts.Count) - loopAt = (int)CountNum.Value; + if (PatternList.SelectedIndex == _counts.Count) + { + _loopAt = (int)CountNum.Value; + } else - counts[PatternList.SelectedIndex] = (int)CountNum.Value; + { + _counts[PatternList.SelectedIndex] = (int)CountNum.Value; + } + UpdatePattern(); UpdateDisplay(); } - private bool _updating = false; private void UpdateDisplay() { _updating = true; @@ -127,52 +149,71 @@ namespace BizHawk.Client.EmuHawk int oldIndex = PatternList.SelectedIndex; if (oldIndex == -1) + { oldIndex = 0; + } PatternList.Items.Clear(); int index = 0; - for (int i = 0; i < counts.Count; i++) + for (int i = 0; i < _counts.Count; i++) { - string str = index.ToString() + ": "; - if (isBool) - str += values[i][0] == 'T' ? "On" : "Off"; + string str = index + ": "; + if (IsBool) + { + str += _values[i][0] == 'T' ? "On" : "Off"; + } else - str += values[i].ToString(); + { + str += _values[i]; + } - PatternList.Items.Add(str + ("\t(x" + counts[i] + ")")); - index += counts[i]; + PatternList.Items.Add(str + ("\t(x" + _counts[i] + ")")); + index += _counts[i]; } - PatternList.Items.Add("Loop to: " + loopAt); + + PatternList.Items.Add("Loop to: " + _loopAt); if (oldIndex >= PatternList.Items.Count) + { oldIndex = PatternList.Items.Count - 1; + } + PatternList.SelectedIndex = oldIndex; - if (PatternList.SelectedIndex != -1 && PatternList.SelectedIndex < values.Count) + if (PatternList.SelectedIndex != -1 && PatternList.SelectedIndex < _values.Count) { - index = Global.MovieSession.MovieControllerAdapter.Definition.BoolButtons.IndexOf(selectedButton); - if (selectedButton == "Default bool Auto-Fire") - index = tastudio.BoolPatterns.Length + 1; + index = Global.MovieSession.MovieControllerAdapter.Definition.BoolButtons.IndexOf(SelectedButton); + if (SelectedButton == "Default bool Auto-Fire") + { + index = _tastudio.BoolPatterns.Length + 1; + } + if (index != -1) { - LagBox.Checked = tastudio.BoolPatterns[index].SkipsLag; - OnOffBox.Checked = values[PatternList.SelectedIndex][0] == 'T'; - CountNum.Value = (decimal)counts[PatternList.SelectedIndex]; + LagBox.Checked = _tastudio.BoolPatterns[index].SkipsLag; + OnOffBox.Checked = _values[PatternList.SelectedIndex][0] == 'T'; + CountNum.Value = _counts[PatternList.SelectedIndex]; } else { - if (selectedButton == "Default float Auto-Fire") - index = tastudio.FloatPatterns.Length + 1; + if (SelectedButton == "Default float Auto-Fire") + { + index = _tastudio.FloatPatterns.Length + 1; + } else - index = Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(selectedButton); + { + index = Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(SelectedButton); + } - LagBox.Checked = tastudio.FloatPatterns[index].SkipsLag; - ValueNum.Value = Convert.ToDecimal(values[PatternList.SelectedIndex]); - CountNum.Value = (decimal)counts[PatternList.SelectedIndex]; + LagBox.Checked = _tastudio.FloatPatterns[index].SkipsLag; + ValueNum.Value = Convert.ToDecimal(_values[PatternList.SelectedIndex]); + CountNum.Value = _counts[PatternList.SelectedIndex]; } } - else if (PatternList.SelectedIndex == values.Count) - CountNum.Value = (decimal)loopAt; + else if (PatternList.SelectedIndex == _values.Count) + { + CountNum.Value = _loopAt; + } PatternList.ResumeLayout(); _updating = false; @@ -180,91 +221,116 @@ namespace BizHawk.Client.EmuHawk private void UpdatePattern() { - int index = Global.MovieSession.MovieControllerAdapter.Definition.BoolButtons.IndexOf(selectedButton); - if (selectedButton == "Default bool Auto-Fire") - index = tastudio.BoolPatterns.Length + 1; + int index = Global.MovieSession.MovieControllerAdapter.Definition.BoolButtons.IndexOf(SelectedButton); + if (SelectedButton == "Default bool Auto-Fire") + { + index = _tastudio.BoolPatterns.Length + 1; + } + if (index != -1) { List p = new List(); - for (int i = 0; i < counts.Count; i++) + for (int i = 0; i < _counts.Count; i++) { - for (int c = 0; c < counts[i]; c++) - p.Add(Convert.ToBoolean(values[i])); + for (int c = 0; c < _counts[i]; c++) + { + p.Add(Convert.ToBoolean(_values[i])); + } } - tastudio.BoolPatterns[index] = new AutoPatternBool(p.ToArray(), LagBox.Checked, 0, loopAt); + + _tastudio.BoolPatterns[index] = new AutoPatternBool(p.ToArray(), LagBox.Checked, 0, _loopAt); } else { - if (selectedButton == "Default float Auto-Fire") - index = tastudio.FloatPatterns.Length + 1; - else - index = Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(selectedButton); - List p = new List(); - for (int i = 0; i < counts.Count; i++) + if (SelectedButton == "Default float Auto-Fire") { - for (int c = 0; c < counts[i]; c++) - p.Add(Convert.ToSingle(values[i])); + index = _tastudio.FloatPatterns.Length + 1; } - tastudio.FloatPatterns[index] = new AutoPatternFloat(p.ToArray(), LagBox.Checked, 0, loopAt); + else + { + index = Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(SelectedButton); + } + + List p = new List(); + for (int i = 0; i < _counts.Count; i++) + { + for (int c = 0; c < _counts[i]; c++) + { + p.Add(Convert.ToSingle(_values[i])); + } + } + + _tastudio.FloatPatterns[index] = new AutoPatternFloat(p.ToArray(), LagBox.Checked, 0, _loopAt); } - tastudio.UpdateAutoFire(selectedButton, null); + _tastudio.UpdateAutoFire(SelectedButton, null); } private void GetPattern() { - int index = Global.MovieSession.MovieControllerAdapter.Definition.BoolButtons.IndexOf(selectedButton); - if (selectedButton == "Default bool Auto-Fire") - index = tastudio.BoolPatterns.Length + 1; + int index = Global.MovieSession.MovieControllerAdapter.Definition.BoolButtons.IndexOf(SelectedButton); + if (SelectedButton == "Default bool Auto-Fire") + { + index = _tastudio.BoolPatterns.Length + 1; + } + if (index != -1) { - bool[] p = tastudio.BoolPatterns[index].Pattern; + bool[] p = _tastudio.BoolPatterns[index].Pattern; bool lastValue = p[0]; - counts.Clear(); - values.Clear(); - counts.Add(1); - values.Add(lastValue.ToString()); + _counts.Clear(); + _values.Clear(); + _counts.Add(1); + _values.Add(lastValue.ToString()); for (int i = 1; i < p.Length; i++) { if (p[i] == lastValue) - counts[counts.Count - 1]++; + { + _counts[_counts.Count - 1]++; + } else { - counts.Add(1); - values.Add(p[i].ToString()); + _counts.Add(1); + _values.Add(p[i].ToString()); lastValue = p[i]; } } - loopAt = tastudio.BoolPatterns[index].Loop; + + _loopAt = _tastudio.BoolPatterns[index].Loop; } else { - if (selectedButton == "Default float Auto-Fire") - index = tastudio.FloatPatterns.Length + 1; + if (SelectedButton == "Default float Auto-Fire") + { + index = _tastudio.FloatPatterns.Length + 1; + } else - index = Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(selectedButton); - float[] p = tastudio.FloatPatterns[index].Pattern; + { + index = Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(SelectedButton); + } + + float[] p = _tastudio.FloatPatterns[index].Pattern; float lastValue = p[0]; - counts.Clear(); - values.Clear(); - counts.Add(1); - values.Add(lastValue.ToString()); + _counts.Clear(); + _values.Clear(); + _counts.Add(1); + _values.Add(lastValue.ToString()); for (int i = 1; i < p.Length; i++) { if (p[i] == lastValue) - counts[counts.Count - 1]++; + { + _counts[_counts.Count - 1]++; + } else { - counts.Add(1); - values.Add(p[i].ToString()); + _counts.Add(1); + _values.Add(p[i].ToString()); lastValue = p[i]; } } - loopAt = tastudio.FloatPatterns[index].Loop; + + _loopAt = _tastudio.FloatPatterns[index].Loop; } } - - - } } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs index 17836ddd76..3391571b85 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/PlaybackBox.cs @@ -1,10 +1,5 @@ using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Linq; -using System.Text; using System.Windows.Forms; using BizHawk.Client.Common; @@ -18,7 +13,7 @@ namespace BizHawk.Client.EmuHawk public TAStudio Tastudio { get; set; } [Browsable(true)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool TurboSeek { get @@ -33,7 +28,7 @@ namespace BizHawk.Client.EmuHawk } [Browsable(true)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool AutoRestore { get @@ -48,7 +43,7 @@ namespace BizHawk.Client.EmuHawk } [Browsable(true)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool FollowCursor { get @@ -63,7 +58,7 @@ namespace BizHawk.Client.EmuHawk } [Browsable(true)] - [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool RecordingMode { get @@ -83,6 +78,7 @@ namespace BizHawk.Client.EmuHawk { Global.MovieSession.Movie.SwitchToPlay(); } + GlobalWin.MainForm.SetMainformMovieInfo(); } } @@ -191,7 +187,5 @@ namespace BizHawk.Client.EmuHawk { GlobalWin.MainForm.HoldFrameAdvance = false; } - - } } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/ScreenshotForm.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/ScreenshotForm.cs index ac89eb228f..4b86d7ee8b 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/ScreenshotForm.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/ScreenshotForm.cs @@ -1,32 +1,30 @@ -// We pretend it's a tooltip kind of thing, so show only the actual contents -// and avoid stealing forcus, while still being topmost -// http://stackoverflow.com/a/25219399/2792852 -// This is not an actual tooltip, because they can't reliably fade in and out with trasparency - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; +using System.Drawing; using System.Windows.Forms; -using BizHawk.Client.Common; +using BizHawk.Client.Common; + +// We pretend it's a tooltip kind of thing, so show only the actual contents +// and avoid stealing forcus, while still being topmost +// http://stackoverflow.com/a/25219399/2792852 +// This is not an actual tooltip, because they can't reliably fade in and out with trasparency namespace BizHawk.Client.EmuHawk { public partial class ScreenshotForm : Form - { - private Timer _showTimer = new Timer(); - private Timer _hideTimer = new Timer(); - private int _widthCap = 320; - private int _heightCap = 240; - private int _interval = 40; - private double _alphaStep = 0.125; - public TasBranch Branch { get; set; } - public FontStyle FontStyle; - public int FontSize; - public int DrawingHeight; + { + // but still appear topmost + private const int WS_EX_TOPMOST = 0x00000008; + + private const int WidthCap = 320; + private const int HeightCap = 240; + private const int Interval = 40; + private const double AlphaStep = 0.125; + + private readonly Timer _showTimer = new Timer(); + private readonly Timer _hideTimer = new Timer(); + + private TasBranch _branch; + private int _drawingHeight; + new public Font Font; new public int Padding; new public string Text; @@ -35,67 +33,73 @@ namespace BizHawk.Client.EmuHawk { InitializeComponent(); - Width = _widthCap; - Height = _heightCap; - FontSize = 10; - FontStyle = FontStyle.Regular; - Font = new Font(FontFamily.GenericMonospace, FontSize, FontStyle); - DrawingHeight = 0; + Width = WidthCap; + Height = HeightCap; + var fontSize = 10; + var fontStyle = FontStyle.Regular; + Font = new Font(FontFamily.GenericMonospace, fontSize, fontStyle); + _drawingHeight = 0; Padding = 0; Opacity = 0; - _showTimer.Interval = _interval; - _showTimer.Tick += new EventHandler((sender, e) => + _showTimer.Interval = Interval; + _showTimer.Tick += (sender, e) => { - if ((Opacity += _alphaStep) >= 1) + if ((Opacity += AlphaStep) >= 1) + { _showTimer.Stop(); - }); + } + }; - _hideTimer.Interval = _interval; - _hideTimer.Tick += new EventHandler((sender, e) => + _hideTimer.Interval = Interval; + _hideTimer.Tick += (sender, e) => { - if ((Opacity -= _alphaStep) <= 0) + if ((Opacity -= AlphaStep) <= 0) { _hideTimer.Stop(); Hide(); } - }); + }; } public void UpdateValues(TasBranch branch, Point location , int width, int height, int padding) { - Branch = branch; + _branch = branch; Width = width; Padding = padding; - DrawingHeight = height; - Text = Branch.UserText; + _drawingHeight = height; + Text = _branch.UserText; Location = location; // Set the screenshot to "1x" resolution of the core // cores like n64 and psx are going to still have sizes too big for the control, so cap them - if (Width > _widthCap) + if (Width > WidthCap) { - double ratio = (double)_widthCap / (double)Width; - Width = _widthCap; - DrawingHeight = (int)((double)(DrawingHeight) * ratio); + double ratio = WidthCap / (double)Width; + Width = WidthCap; + _drawingHeight = (int)((double)(_drawingHeight) * ratio); } if (Padding > 0) + { Padding += 2; - Height = DrawingHeight + Padding; + } + + Height = _drawingHeight + Padding; Refresh(); } protected override void OnPaint(PaintEventArgs e) { - Branch.OSDFrameBuffer.DiscardAlpha(); - var bitmap = Branch.OSDFrameBuffer.ToSysdrawingBitmap(); - e.Graphics.DrawImage(bitmap, new Rectangle(0, 0, Width, DrawingHeight)); + _branch.OSDFrameBuffer.DiscardAlpha(); + var bitmap = _branch.OSDFrameBuffer.ToSysdrawingBitmap(); + e.Graphics.DrawImage(bitmap, new Rectangle(0, 0, Width, _drawingHeight)); if (Padding > 0) { - e.Graphics.DrawRectangle(new Pen(Brushes.Black), new Rectangle(new Point(0, DrawingHeight), new Size(Width - 1, Padding - 1))); - e.Graphics.DrawString(Text, Font, Brushes.Black, new Rectangle(2, DrawingHeight, Width - 2, Height)); + e.Graphics.DrawRectangle(new Pen(Brushes.Black), new Rectangle(new Point(0, _drawingHeight), new Size(Width - 1, Padding - 1))); + e.Graphics.DrawString(Text, Font, Brushes.Black, new Rectangle(2, _drawingHeight, Width - 2, Height)); } + base.OnPaint(e); } @@ -115,13 +119,8 @@ namespace BizHawk.Client.EmuHawk } // avoid stealing focus - protected override bool ShowWithoutActivation - { - get { return true; } - } + protected override bool ShowWithoutActivation => true; - // but still appear topmost - private const int WS_EX_TOPMOST = 0x00000008; protected override CreateParams CreateParams { get diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Callbacks.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Callbacks.cs index 98353e28b4..1cc4ba50b5 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Callbacks.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Callbacks.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.Drawing; -using System.Linq; namespace BizHawk.Client.EmuHawk { @@ -16,40 +14,22 @@ namespace BizHawk.Client.EmuHawk private Color? GetColorOverride(int index, InputRoll.RollColumn column) { - if (QueryItemBgColorCallback != null) - { - return QueryItemBgColorCallback(index, column.Name); - } - - return null; + return QueryItemBgColorCallback?.Invoke(index, column.Name); } private string GetTextOverride(int index, InputRoll.RollColumn column) { - if (QueryItemTextCallback != null) - { - return QueryItemTextCallback(index, column.Name); - } - - return null; + return QueryItemTextCallback?.Invoke(index, column.Name); } private Bitmap GetIconOverride(int index, InputRoll.RollColumn column) { - if (QueryItemIconCallback != null) - { - return QueryItemIconCallback(index, column.Name); - } - - return null; + return QueryItemIconCallback?.Invoke(index, column.Name); } private void GreenzoneInvalidated(int index) { - if (GreenzoneInvalidatedCallback != null) - { - GreenzoneInvalidatedCallback(index); - } + GreenzoneInvalidatedCallback?.Invoke(index); } } } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Designer.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Designer.cs index ea2f14858a..fd7640905f 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Designer.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Designer.cs @@ -348,14 +348,14 @@ namespace BizHawk.Client.EmuHawk this.saveSelectionToMacroToolStripMenuItem.Name = "saveSelectionToMacroToolStripMenuItem"; this.saveSelectionToMacroToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.saveSelectionToMacroToolStripMenuItem.Text = "Save Selection to Macro"; - this.saveSelectionToMacroToolStripMenuItem.Click += new System.EventHandler(this.saveSelectionToMacroToolStripMenuItem_Click); + this.saveSelectionToMacroToolStripMenuItem.Click += new System.EventHandler(this.SaveSelectionToMacroMenuItem_Click); // // placeMacroAtSelectionToolStripMenuItem // this.placeMacroAtSelectionToolStripMenuItem.Name = "placeMacroAtSelectionToolStripMenuItem"; this.placeMacroAtSelectionToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.placeMacroAtSelectionToolStripMenuItem.Text = "Place Macro at Selection"; - this.placeMacroAtSelectionToolStripMenuItem.Click += new System.EventHandler(this.placeMacroAtSelectionToolStripMenuItem_Click); + this.placeMacroAtSelectionToolStripMenuItem.Click += new System.EventHandler(this.PlaceMacroAtSelectionMenuItem_Click); // // recentMacrosToolStripMenuItem // @@ -365,7 +365,7 @@ namespace BizHawk.Client.EmuHawk this.recentMacrosToolStripMenuItem.Name = "recentMacrosToolStripMenuItem"; this.recentMacrosToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.recentMacrosToolStripMenuItem.Text = "Recent Macros"; - this.recentMacrosToolStripMenuItem.DropDownOpened += new System.EventHandler(this.recentMacrosToolStripMenuItem_DropDownOpened); + this.recentMacrosToolStripMenuItem.DropDownOpened += new System.EventHandler(this.RecentMacrosMenuItem_DropDownOpened); // // toolStripSeparator22 // @@ -453,7 +453,7 @@ namespace BizHawk.Client.EmuHawk this.showUndoHistoryToolStripMenuItem.Name = "showUndoHistoryToolStripMenuItem"; this.showUndoHistoryToolStripMenuItem.Size = new System.Drawing.Size(291, 22); this.showUndoHistoryToolStripMenuItem.Text = "Show Undo History"; - this.showUndoHistoryToolStripMenuItem.Click += new System.EventHandler(this.showUndoHistoryToolStripMenuItem_Click); + this.showUndoHistoryToolStripMenuItem.Click += new System.EventHandler(this.ShowUndoHistoryMenuItem_Click); // // SelectionUndoMenuItem // @@ -753,7 +753,7 @@ namespace BizHawk.Client.EmuHawk this.applyPatternToPaintedInputToolStripMenuItem.Name = "applyPatternToPaintedInputToolStripMenuItem"; this.applyPatternToPaintedInputToolStripMenuItem.Size = new System.Drawing.Size(255, 22); this.applyPatternToPaintedInputToolStripMenuItem.Text = "Apply Pattern to painted input"; - this.applyPatternToPaintedInputToolStripMenuItem.CheckedChanged += new System.EventHandler(this.applyPatternToPaintedInputToolStripMenuItem_CheckedChanged); + this.applyPatternToPaintedInputToolStripMenuItem.CheckedChanged += new System.EventHandler(this.ApplyPatternToPaintedInputMenuItem_CheckedChanged); // // onlyOnAutoFireColumnsToolStripMenuItem // @@ -872,7 +872,7 @@ namespace BizHawk.Client.EmuHawk this.autoHoldToolStripMenuItem.Name = "autoHoldToolStripMenuItem"; this.autoHoldToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.autoHoldToolStripMenuItem.Text = "Auto-Hold"; - this.autoHoldToolStripMenuItem.CheckedChanged += new System.EventHandler(this.autoHoldToolStripMenuItem_CheckedChanged); + this.autoHoldToolStripMenuItem.CheckedChanged += new System.EventHandler(this.AutoHoldMenuItem_CheckedChanged); // // autoFireToolStripMenuItem // @@ -880,7 +880,7 @@ namespace BizHawk.Client.EmuHawk this.autoFireToolStripMenuItem.Name = "autoFireToolStripMenuItem"; this.autoFireToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.autoFireToolStripMenuItem.Text = "Auto-Fire"; - this.autoFireToolStripMenuItem.CheckedChanged += new System.EventHandler(this.autoFireToolStripMenuItem_CheckedChanged); + this.autoFireToolStripMenuItem.CheckedChanged += new System.EventHandler(this.AutoFireMenuItem_CheckedChanged); // // customPatternToolStripMenuItem // @@ -888,7 +888,7 @@ namespace BizHawk.Client.EmuHawk this.customPatternToolStripMenuItem.Name = "customPatternToolStripMenuItem"; this.customPatternToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.customPatternToolStripMenuItem.Text = "Custom Pattern"; - this.customPatternToolStripMenuItem.CheckedChanged += new System.EventHandler(this.customPatternToolStripMenuItem_CheckedChanged); + this.customPatternToolStripMenuItem.CheckedChanged += new System.EventHandler(this.CustomPatternMenuItem_CheckedChanged); // // setpToolStripMenuItem // @@ -900,7 +900,7 @@ namespace BizHawk.Client.EmuHawk this.setCustomsToolStripMenuItem.Name = "setCustomsToolStripMenuItem"; this.setCustomsToolStripMenuItem.Size = new System.Drawing.Size(171, 22); this.setCustomsToolStripMenuItem.Text = "Set Customs..."; - this.setCustomsToolStripMenuItem.Click += new System.EventHandler(this.setCustomsToolStripMenuItem_Click); + this.setCustomsToolStripMenuItem.Click += new System.EventHandler(this.SetCustomsMenuItem_Click); // // MetaSubMenu // @@ -1039,7 +1039,7 @@ namespace BizHawk.Client.EmuHawk this.hideWasLagFramesToolStripMenuItem.Name = "hideWasLagFramesToolStripMenuItem"; this.hideWasLagFramesToolStripMenuItem.Size = new System.Drawing.Size(185, 22); this.hideWasLagFramesToolStripMenuItem.Text = "Hide WasLag Frames"; - this.hideWasLagFramesToolStripMenuItem.Click += new System.EventHandler(this.hideWasLagFramesToolStripMenuItem_Click); + this.hideWasLagFramesToolStripMenuItem.Click += new System.EventHandler(this.HideWasLagFramesMenuItem_Click); // // iconsToolStripMenuItem // @@ -1051,7 +1051,7 @@ namespace BizHawk.Client.EmuHawk this.iconsToolStripMenuItem.Name = "iconsToolStripMenuItem"; this.iconsToolStripMenuItem.Size = new System.Drawing.Size(188, 22); this.iconsToolStripMenuItem.Text = "Icons"; - this.iconsToolStripMenuItem.DropDownOpened += new System.EventHandler(this.iconsToolStripMenuItem_DropDownOpened); + this.iconsToolStripMenuItem.DropDownOpened += new System.EventHandler(this.IconsMenuItem_DropDownOpened); // // DenoteStatesWithIconsToolStripMenuItem // @@ -1102,7 +1102,7 @@ namespace BizHawk.Client.EmuHawk this.followCursorToolStripMenuItem.Name = "followCursorToolStripMenuItem"; this.followCursorToolStripMenuItem.Size = new System.Drawing.Size(188, 22); this.followCursorToolStripMenuItem.Text = "Follow Cursor"; - this.followCursorToolStripMenuItem.DropDownOpened += new System.EventHandler(this.followCursorToolStripMenuItem_DropDownOpened); + this.followCursorToolStripMenuItem.DropDownOpened += new System.EventHandler(this.FollowCursorMenuItem_DropDownOpened); // // alwaysScrollToolStripMenuItem // @@ -1110,7 +1110,7 @@ namespace BizHawk.Client.EmuHawk this.alwaysScrollToolStripMenuItem.Name = "alwaysScrollToolStripMenuItem"; this.alwaysScrollToolStripMenuItem.Size = new System.Drawing.Size(160, 22); this.alwaysScrollToolStripMenuItem.Text = "Always Scroll"; - this.alwaysScrollToolStripMenuItem.Click += new System.EventHandler(this.alwaysScrollToolStripMenuItem_Click); + this.alwaysScrollToolStripMenuItem.Click += new System.EventHandler(this.AlwaysScrollMenuItem_Click); // // toolStripSeparator24 // @@ -1125,7 +1125,7 @@ namespace BizHawk.Client.EmuHawk this.scrollToViewToolStripMenuItem.Name = "scrollToViewToolStripMenuItem"; this.scrollToViewToolStripMenuItem.Size = new System.Drawing.Size(160, 22); this.scrollToViewToolStripMenuItem.Text = "Scroll to View"; - this.scrollToViewToolStripMenuItem.Click += new System.EventHandler(this.scrollToViewToolStripMenuItem_Click); + this.scrollToViewToolStripMenuItem.Click += new System.EventHandler(this.ScrollToViewMenuItem_Click); // // scrollToTopToolStripMenuItem // @@ -1133,7 +1133,7 @@ namespace BizHawk.Client.EmuHawk this.scrollToTopToolStripMenuItem.Name = "scrollToTopToolStripMenuItem"; this.scrollToTopToolStripMenuItem.Size = new System.Drawing.Size(160, 22); this.scrollToTopToolStripMenuItem.Text = "Scroll to Top"; - this.scrollToTopToolStripMenuItem.Click += new System.EventHandler(this.scrollToTopToolStripMenuItem_Click); + this.scrollToTopToolStripMenuItem.Click += new System.EventHandler(this.ScrollToTopMenuItem_Click); // // scrollToBottomToolStripMenuItem // @@ -1141,7 +1141,7 @@ namespace BizHawk.Client.EmuHawk this.scrollToBottomToolStripMenuItem.Name = "scrollToBottomToolStripMenuItem"; this.scrollToBottomToolStripMenuItem.Size = new System.Drawing.Size(160, 22); this.scrollToBottomToolStripMenuItem.Text = "Scroll to Bottom"; - this.scrollToBottomToolStripMenuItem.Click += new System.EventHandler(this.scrollToBottomToolStripMenuItem_Click); + this.scrollToBottomToolStripMenuItem.Click += new System.EventHandler(this.ScrollToBottomMenuItem_Click); // // scrollToCenterToolStripMenuItem // @@ -1149,7 +1149,7 @@ namespace BizHawk.Client.EmuHawk this.scrollToCenterToolStripMenuItem.Name = "scrollToCenterToolStripMenuItem"; this.scrollToCenterToolStripMenuItem.Size = new System.Drawing.Size(160, 22); this.scrollToCenterToolStripMenuItem.Text = "Scroll to Center"; - this.scrollToCenterToolStripMenuItem.Click += new System.EventHandler(this.scrollToCenterToolStripMenuItem_Click); + this.scrollToCenterToolStripMenuItem.Click += new System.EventHandler(this.ScrollToCenterMenuItem_Click); // // toolStripSeparator25 // @@ -1161,7 +1161,7 @@ namespace BizHawk.Client.EmuHawk this.wheelScrollSpeedToolStripMenuItem.Name = "wheelScrollSpeedToolStripMenuItem"; this.wheelScrollSpeedToolStripMenuItem.Size = new System.Drawing.Size(188, 22); this.wheelScrollSpeedToolStripMenuItem.Text = "Wheel Scroll Speed..."; - this.wheelScrollSpeedToolStripMenuItem.Click += new System.EventHandler(this.wheelScrollSpeedToolStripMenuItem_Click); + this.wheelScrollSpeedToolStripMenuItem.Click += new System.EventHandler(this.WheelScrollSpeedMenuItem_Click); // // ColumnsSubMenu // @@ -1227,7 +1227,7 @@ namespace BizHawk.Client.EmuHawk // this.TasView.AllowColumnReorder = false; this.TasView.AllowColumnResize = false; - this.TasView.allowRightClickSelecton = false; + this.TasView.AllowRightClickSelecton = false; this.TasView.AlwaysScroll = false; this.TasView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) @@ -1238,7 +1238,7 @@ namespace BizHawk.Client.EmuHawk this.TasView.HideWasLagFrames = false; this.TasView.HorizontalOrientation = false; this.TasView.LagFramesToHide = 0; - this.TasView.letKeysModifySelection = true; + this.TasView.LetKeysModifySelection = true; this.TasView.Location = new System.Drawing.Point(3, 0); this.TasView.MaxCharactersInHorizontal = 1; this.TasView.MultiSelect = false; @@ -1247,7 +1247,7 @@ namespace BizHawk.Client.EmuHawk this.TasView.ScrollSpeed = 1; this.TasView.SeekingCutoffInterval = 0; this.TasView.Size = new System.Drawing.Size(289, 528); - this.TasView.suspendHotkeys = false; + this.TasView.SuspendHotkeys = false; this.TasView.TabIndex = 1; this.TasView.ColumnClick += new BizHawk.Client.EmuHawk.InputRoll.ColumnClickEventHandler(this.TasView_ColumnClick); this.TasView.ColumnRightClick += new BizHawk.Client.EmuHawk.InputRoll.ColumnClickEventHandler(this.TasView_ColumnRightClick); diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs index 9d1ba1d710..8abd471b26 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IControlMainForm.cs @@ -1,53 +1,59 @@ -using System; -using System.Collections.Generic; -namespace BizHawk.Client.EmuHawk +namespace BizHawk.Client.EmuHawk { public partial class TAStudio : IControlMainform { - private bool _suppressAskSave = false; + private bool _suppressAskSave; - public bool NamedStatePending = false; + public bool NamedStatePending { get; set; } - public bool WantsToControlSavestates { get { return !NamedStatePending; } } + public bool WantsToControlSavestates => !NamedStatePending; public void SaveState() { BookMarkControl.UpdateBranchExternal(); } + public void LoadState() { BookMarkControl.LoadBranchExternal(); } + public void SaveStateAs() { // dummy } + public void LoadStateAs() { // dummy } + public void SaveQuickSave(int slot) { BookMarkControl.UpdateBranchExternal(slot); } + public void LoadQuickSave(int slot) { BookMarkControl.LoadBranchExternal(slot); } + public void SelectSlot(int slot) { BookMarkControl.SelectBranchExternal(slot); } + public void PreviousSlot() { BookMarkControl.SelectBranchExternal(false); } + public void NextSlot() { BookMarkControl.SelectBranchExternal(true); } - public bool WantsToControlReadOnly { get { return true; } } + public bool WantsToControlReadOnly => true; public void ToggleReadOnly() { @@ -65,13 +71,13 @@ namespace BizHawk.Client.EmuHawk public void StopMovie(bool supressSave) { - this.Focus(); + Focus(); _suppressAskSave = supressSave; NewTasMenuItem_Click(null, null); _suppressAskSave = false; } - public bool WantsToControlRewind { get { return true; } } + public bool WantsToControlRewind => true; public void CaptureRewind() { @@ -84,6 +90,7 @@ namespace BizHawk.Client.EmuHawk if (Mainform.IsSeeking && !Mainform.EmulatorPaused) { Mainform.PauseOnFrame--; + // that's a weird condition here, but for whatever reason it works best if (Emulator.Frame >= Mainform.PauseOnFrame) { @@ -92,17 +99,19 @@ namespace BizHawk.Client.EmuHawk StopSeeking(); GoToPreviousFrame(); } + RefreshDialog(); } else { - StopSeeking(); //late breaking memo: dont know whether this is needed + StopSeeking(); // late breaking memo: dont know whether this is needed GoToPreviousFrame(); } + return true; } - public bool WantsToControlRestartMovie { get; private set; } + public bool WantsToControlRestartMovie { get; } public void RestartMovie() { diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IToolForm.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IToolForm.cs index d931c2c6ae..c08edc405d 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IToolForm.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.IToolForm.cs @@ -1,7 +1,6 @@ using System.Windows.Forms; + using BizHawk.Client.Common; -using System.Collections.Generic; -using System; using BizHawk.Emulation.Common; namespace BizHawk.Client.EmuHawk @@ -23,33 +22,46 @@ namespace BizHawk.Client.EmuHawk private bool _hackyDontUpdate; private bool _initializing; // If true, will bypass restart logic, this is necessary since loading projects causes a movie to load which causes a rom to reload causing dialogs to restart - public bool UpdateBefore { get { return false; } } + public bool UpdateBefore => false; public void NewUpdate(ToolFormUpdateType type) { } - private int lastRefresh = 0; + private int _lastRefresh; + public void UpdateValues() { if (!IsHandleCreated || IsDisposed || CurrentTasMovie == null) + { return; + } if (_hackyDontUpdate) + { return; + } if (_exiting) + { return; + } bool refreshNeeded = false; if (AutoadjustInputMenuItem.Checked) + { refreshNeeded = AutoAdjustInput(); + } if (TasView.RowCount != CurrentTasMovie.InputLogLength + 1) + { TasView.RowCount = CurrentTasMovie.InputLogLength + 1; + } MaybeFollowCursor(); - if (TasView.IsPartiallyVisible(Emulator.Frame) || TasView.IsPartiallyVisible(lastRefresh)) + if (TasView.IsPartiallyVisible(Emulator.Frame) || TasView.IsPartiallyVisible(_lastRefresh)) + { refreshNeeded = true; + } RefreshDialog(refreshNeeded); } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs index 151509bd46..295976bb22 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.ListView.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Windows.Forms; using System.Collections.Generic; -using BizHawk.Emulation.Common.IEmulatorExtensions; +using BizHawk.Emulation.Common; using BizHawk.Common.NumberExtensions; using BizHawk.Client.Common; @@ -29,12 +29,18 @@ namespace BizHawk.Client.EmuHawk private int _floatEditRow = -1; private string _floatTypedValue; private int _floatEditYPos = -1; - private int floatEditRow { set { - _floatEditRow = value; - TasView.suspendHotkeys = FloatEditingMode; - } } - public bool FloatEditingMode { get { return _floatEditRow != -1; } } - private List _extraFloatRows = new List(); + private int floatEditRow + { + set + { + _floatEditRow = value; + TasView.SuspendHotkeys = FloatEditingMode; + } + } + + public bool FloatEditingMode => _floatEditRow != -1; + + private readonly List _extraFloatRows = new List(); // Right-click dragging private string[] _rightClickInput = null; @@ -43,14 +49,17 @@ namespace BizHawk.Client.EmuHawk private int _rightClickLastFrame = -1; private bool _rightClickShift, _rightClickControl, _rightClickAlt; private bool _leftButtonHeld = false; - private bool mouseButtonHeld { get { return _rightClickFrame != -1 || _leftButtonHeld; } } + + private bool MouseButtonHeld => _rightClickFrame != -1 || _leftButtonHeld; + private bool _triggerAutoRestore; // If true, autorestore will be called on mouse up private bool? _autoRestorePaused = null; private int? _seekStartFrame = null; private bool _shouldUnpauseFromRewind = false; - private Emulation.Common.ControllerDefinition controllerType { get { - return Global.MovieSession.MovieControllerAdapter.Definition; } } - public bool WasRecording = false; + + private ControllerDefinition ControllerType => Global.MovieSession.MovieControllerAdapter.Definition; + + public bool WasRecording; public AutoPatternBool[] BoolPatterns; public AutoPatternFloat[] FloatPatterns; @@ -69,10 +78,14 @@ namespace BizHawk.Client.EmuHawk private void StartSeeking(int? frame) { if (!frame.HasValue) + { return; + } if (Mainform.PauseOnFrame != null) + { StopSeeking(true); // don't restore rec mode just yet, as with heavy editing checkbox updating causes lag + } _seekStartFrame = Emulator.Frame; Mainform.PauseOnFrame = frame.Value; @@ -83,7 +96,9 @@ namespace BizHawk.Client.EmuHawk Mainform.UnpauseEmulator(); if (!_seekBackgroundWorker.IsBusy && diff.Value > TasView.VisibleRows) + { _seekBackgroundWorker.RunWorkerAsync(); + } } public void StopSeeking(bool skipRecModeCheck = false) @@ -94,45 +109,49 @@ namespace BizHawk.Client.EmuHawk TastudioRecordMode(); WasRecording = false; } + Mainform.PauseOnFrame = null; if (_shouldUnpauseFromRewind) { Mainform.UnpauseEmulator(); _shouldUnpauseFromRewind = false; } + if (CurrentTasMovie != null) + { RefreshDialog(); + } } #region Query callbacks // public static Color CurrentFrame_FrameCol = Color.FromArgb(0xCFEDFC); Why? - public static Color CurrentFrame_InputLog = Color.FromArgb(0x00B5E7F7); - public static Color SeekFrame_InputLog = Color.FromArgb(0x70B5E7F7); + public static Color CurrentFrame_InputLog => Color.FromArgb(0x00B5E7F7); + public static Color SeekFrame_InputLog => Color.FromArgb(0x70B5E7F7); - public static Color GreenZone_FrameCol = Color.FromArgb(0xDDFFDD); - public static Color GreenZone_InputLog = Color.FromArgb(0xD2F9D3); - public static Color GreenZone_InputLog_Stated = Color.FromArgb(0xC4F7C8); - public static Color GreenZone_InputLog_Invalidated = Color.FromArgb(0xE0FBE0); + public static Color GreenZone_FrameCol => Color.FromArgb(0xDDFFDD); + public static Color GreenZone_InputLog => Color.FromArgb(0xD2F9D3); + public static Color GreenZone_InputLog_Stated => Color.FromArgb(0xC4F7C8); + public static Color GreenZone_InputLog_Invalidated => Color.FromArgb(0xE0FBE0); - public static Color LagZone_FrameCol = Color.FromArgb(0xFFDCDD); - public static Color LagZone_InputLog = Color.FromArgb(0xF4DADA); - public static Color LagZone_InputLog_Stated = Color.FromArgb(0xF0D0D2); - public static Color LagZone_InputLog_Invalidated = Color.FromArgb(0xF7E5E5); + public static Color LagZone_FrameCol => Color.FromArgb(0xFFDCDD); + public static Color LagZone_InputLog => Color.FromArgb(0xF4DADA); + public static Color LagZone_InputLog_Stated => Color.FromArgb(0xF0D0D2); + public static Color LagZone_InputLog_Invalidated => Color.FromArgb(0xF7E5E5); - public static Color Marker_FrameCol = Color.FromArgb(0xF7FFC9); - public static Color AnalogEdit_Col = Color.FromArgb(0x909070); // SuuperW: When editing an analog value, it will be a gray color. + public static Color Marker_FrameCol => Color.FromArgb(0xF7FFC9); + public static Color AnalogEdit_Col => Color.FromArgb(0x909070); // SuuperW: When editing an analog value, it will be a gray color. - private Bitmap ts_v_arrow_green_blue = Properties.Resources.ts_v_arrow_green_blue; - private Bitmap ts_h_arrow_green_blue = Properties.Resources.ts_h_arrow_green_blue; - private Bitmap ts_v_arrow_blue = Properties.Resources.ts_v_arrow_blue; - private Bitmap ts_h_arrow_blue = Properties.Resources.ts_h_arrow_blue; - private Bitmap ts_v_arrow_green = Properties.Resources.ts_v_arrow_green; - private Bitmap ts_h_arrow_green = Properties.Resources.ts_h_arrow_green; + private Bitmap ts_v_arrow_green_blue => Properties.Resources.ts_v_arrow_green_blue; + private Bitmap ts_h_arrow_green_blue => Properties.Resources.ts_h_arrow_green_blue; + private Bitmap ts_v_arrow_blue => Properties.Resources.ts_v_arrow_blue; + private Bitmap ts_h_arrow_blue => Properties.Resources.ts_h_arrow_blue; + private Bitmap ts_v_arrow_green => Properties.Resources.ts_v_arrow_green; + private Bitmap ts_h_arrow_green => Properties.Resources.ts_h_arrow_green; - private Bitmap icon_marker = Properties.Resources.icon_marker; - private Bitmap icon_anchor_lag = Properties.Resources.icon_anchor_lag; - private Bitmap icon_anchor = Properties.Resources.icon_anchor; + private Bitmap icon_marker => Properties.Resources.icon_marker; + private Bitmap icon_anchor_lag => Properties.Resources.icon_anchor_lag; + private Bitmap icon_anchor => Properties.Resources.icon_anchor; private void TasView_QueryItemIcon(int index, InputRoll.RollColumn column, ref Bitmap bitmap, ref int offsetX, ref int offsetY) { @@ -174,13 +193,19 @@ namespace BizHawk.Client.EmuHawk offsetY = 1; if (CurrentTasMovie.Markers.IsMarker(index) && Settings.DenoteMarkersWithIcons) + { bitmap = icon_marker; + } else if (record.HasState && Settings.DenoteStatesWithIcons) { if (record.Lagged.HasValue && record.Lagged.Value) + { bitmap = icon_anchor_lag; + } else + { bitmap = icon_anchor; + } } } } @@ -203,20 +228,27 @@ namespace BizHawk.Client.EmuHawk if (columnName == FrameColumnName) { if (Emulator.Frame != index && CurrentTasMovie.Markers.IsMarker(index) && Settings.DenoteMarkersWithBGColor) + { color = Marker_FrameCol; + } else + { color = Color.FromArgb(0x60FFFFFF); + } } else if (FloatEditingMode && (index == _floatEditRow || _extraFloatRows.Contains(index)) && columnName == _floatEditColumn) - { // SuuperW: Analog editing is indicated by a color change. + { + // SuuperW: Analog editing is indicated by a color change. color = AnalogEdit_Col; } int player = Emulator.ControllerDefinition.PlayerNumber(columnName); if (player != 0 && player % 2 == 0) + { color = Color.FromArgb(0x0D000000); + } } private void TasView_QueryRowBkColor(int index, ref Color color) @@ -234,13 +266,17 @@ namespace BizHawk.Client.EmuHawk else if (record.Lagged.HasValue) { if (!record.HasState && Settings.DenoteStatesWithBGColor) - color = record.Lagged.Value ? - LagZone_InputLog : - GreenZone_InputLog; + { + color = record.Lagged.Value + ? LagZone_InputLog + : GreenZone_InputLog; + } else - color = record.Lagged.Value ? - LagZone_InputLog_Stated : - GreenZone_InputLog_Stated; + { + color = record.Lagged.Value + ? LagZone_InputLog_Stated + : GreenZone_InputLog_Stated; + } } else if (record.WasLagged.HasValue) { @@ -279,23 +315,27 @@ namespace BizHawk.Client.EmuHawk else if (columnName == FrameColumnName) { offsetX = 7; - text = (index).ToString().PadLeft(CurrentTasMovie.InputLogLength.ToString().Length, '0'); + text = index.ToString().PadLeft(CurrentTasMovie.InputLogLength.ToString().Length, '0'); } else { // Display typed float value (string "-" can't be parsed, so CurrentTasMovie.DisplayValue can't return it) if (index == _floatEditRow && columnName == _floatEditColumn) + { text = _floatTypedValue; + } else if (index < CurrentTasMovie.InputLogLength) { text = CurrentTasMovie.DisplayValue(index, columnName); if (column.Type == InputRoll.RollColumn.InputType.Float) { // feos: this could be cashed, but I don't notice any slowdown this way either - Emulation.Common.ControllerDefinition.FloatRange range = Global.MovieSession.MovieControllerAdapter.Definition.FloatRanges + ControllerDefinition.FloatRange range = Global.MovieSession.MovieControllerAdapter.Definition.FloatRanges [Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(columnName)]; if (text == range.Mid.ToString()) + { text = ""; + } } } } @@ -329,32 +369,30 @@ namespace BizHawk.Client.EmuHawk CurrentTasMovie.Markers.Add(TasView.LastSelectedIndex.Value, ""); RefreshDialog(); } - else if (columnName != CursorColumnName) // TODO: what about float? + else if (columnName != CursorColumnName) { int frame = TasView.SelectedRows.FirstOrDefault(); string buttonName = TasView.CurrentCell.Column.Name; if (Global.MovieSession.MovieControllerAdapter.Definition.BoolButtons.Contains(buttonName)) { - bool state = !CurrentTasMovie.BoolIsPressed(frame, buttonName); + // nifty taseditor logic + bool allPressed = true; foreach (var index in TasView.SelectedRows) { - CurrentTasMovie.SetBoolState(index, buttonName, state); + if ((index == CurrentTasMovie.FrameCount) // last movie frame can't have input, but can be selected + || (!CurrentTasMovie.BoolIsPressed(index, buttonName))) + { + allPressed = false; + break; + } } + CurrentTasMovie.SetBoolStates(frame, TasView.SelectedRows.Count(), buttonName, !allPressed); } else { - float state = CurrentTasMovie.GetFloatState(frame, buttonName); - Emulation.Common.ControllerDefinition.FloatRange range = Global.MovieSession.MovieControllerAdapter.Definition.FloatRanges - [Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(columnName)]; - - if (state != range.Mid) - state = range.Mid; - - foreach (var index in TasView.SelectedRows) - { - CurrentTasMovie.SetFloatState(index, buttonName, state); - } + // feos: there's no default value other than mid, and we can't go arbitrary here, so do nothing for now + // autohold is ignored for float input too for the same reasons: lack of demand + ambiguity } _triggerAutoRestore = true; @@ -375,33 +413,59 @@ namespace BizHawk.Client.EmuHawk private void UpdateAutoFire() { for (int i = 2; i < TasView.AllColumns.Count; i++) + { UpdateAutoFire(TasView.AllColumns[i].Name, TasView.AllColumns[i].Emphasis); + } } public void UpdateAutoFire(string button, bool? isOn) { if (!isOn.HasValue) // No value means don't change whether it's on or off. + { isOn = TasView.AllColumns.Find(c => c.Name == button).Emphasis; + } int index = 0; - if (autoHoldToolStripMenuItem.Checked) index = 1; - if (autoFireToolStripMenuItem.Checked) index = 2; - if (controllerType.BoolButtons.Contains(button)) + if (autoHoldToolStripMenuItem.Checked) + { + index = 1; + } + + if (autoFireToolStripMenuItem.Checked) + { + index = 2; + } + + if (ControllerType.BoolButtons.Contains(button)) { if (index == 0) - index = controllerType.BoolButtons.IndexOf(button); + { + index = ControllerType.BoolButtons.IndexOf(button); + } else - index += controllerType.BoolButtons.Count - 1; + { + index += ControllerType.BoolButtons.Count - 1; + } + AutoPatternBool p = BoolPatterns[index]; Global.AutofireStickyXORAdapter.SetSticky(button, isOn.Value, p); } else { if (index == 0) - index = controllerType.FloatControls.IndexOf(button); + { + index = ControllerType.FloatControls.IndexOf(button); + } else - index += controllerType.FloatControls.Count - 1; + { + index += ControllerType.FloatControls.Count - 1; + } + float? value = null; - if (isOn.Value) value = 0f; + if (isOn.Value) + { + value = 0f; + } + AutoPatternFloat p = FloatPatterns[index]; Global.AutofireStickyXORAdapter.SetFloat(button, value, p); } @@ -414,15 +478,19 @@ namespace BizHawk.Client.EmuHawk private void TasView_MouseEnter(object sender, EventArgs e) { - if (this.ContainsFocus) + if (ContainsFocus) + { TasView.Focus(); + } } private void TasView_MouseDown(object sender, MouseEventArgs e) { // Clicking with left while right is held or vice versa does weird stuff - if (mouseButtonHeld) + if (MouseButtonHeld) + { return; + } if (e.Button == MouseButtons.Middle) { @@ -430,20 +498,27 @@ namespace BizHawk.Client.EmuHawk { TasMovieRecord record = CurrentTasMovie[LastPositionFrame]; if (!record.Lagged.HasValue && LastPositionFrame > Emulator.Frame) + { StartSeeking(LastPositionFrame); + } else + { Mainform.UnpauseEmulator(); + } } else { Mainform.PauseEmulator(); } + return; } // SuuperW: Moved these. - if (TasView.CurrentCell == null || !TasView.CurrentCell.RowIndex.HasValue || TasView.CurrentCell.Column == null) + if (TasView.CurrentCell?.RowIndex == null || TasView.CurrentCell.Column == null) + { return; + } int frame = TasView.CurrentCell.RowIndex.Value; string buttonName = TasView.CurrentCell.Column.Name; @@ -453,6 +528,7 @@ namespace BizHawk.Client.EmuHawk { bool wasHeld = _leftButtonHeld; _leftButtonHeld = true; + // SuuperW: Exit float editing mode, or re-enter mouse editing if (FloatEditingMode) { @@ -479,6 +555,7 @@ namespace BizHawk.Client.EmuHawk floatEditRow = frame; RefreshTasView(); } + _floatEditYPos = e.Y; _floatPaintState = CurrentTasMovie.GetFloatState(frame, buttonName); _triggerAutoRestore = true; @@ -521,18 +598,22 @@ namespace BizHawk.Client.EmuHawk _startBoolDrawColumn = buttonName; _boolPaintState = CurrentTasMovie.BoolIsPressed(frame, buttonName); - if (applyPatternToPaintedInputToolStripMenuItem.Checked && - (!onlyOnAutoFireColumnsToolStripMenuItem.Checked || TasView.CurrentCell.Column.Emphasis)) + if (applyPatternToPaintedInputToolStripMenuItem.Checked && (!onlyOnAutoFireColumnsToolStripMenuItem.Checked + || TasView.CurrentCell.Column.Emphasis)) { - BoolPatterns[controllerType.BoolButtons.IndexOf(buttonName)].Reset(); - BoolPatterns[controllerType.BoolButtons.IndexOf(buttonName)].GetNextValue(); + BoolPatterns[ControllerType.BoolButtons.IndexOf(buttonName)].Reset(); + BoolPatterns[ControllerType.BoolButtons.IndexOf(buttonName)].GetNextValue(); _patternPaint = true; } else + { _patternPaint = false; + } if (!Settings.AutoRestoreOnMouseUpOnly) + { DoTriggeredAutoRestoreIfNeeded(); + } } else { @@ -545,16 +626,17 @@ namespace BizHawk.Client.EmuHawk JumpToGreenzone(); _floatPaintState = CurrentTasMovie.GetFloatState(frame, buttonName); - if (applyPatternToPaintedInputToolStripMenuItem.Checked && - (!onlyOnAutoFireColumnsToolStripMenuItem.Checked || TasView.CurrentCell.Column.Emphasis)) + if (applyPatternToPaintedInputToolStripMenuItem.Checked && (!onlyOnAutoFireColumnsToolStripMenuItem.Checked + || TasView.CurrentCell.Column.Emphasis)) { - FloatPatterns[controllerType.FloatControls.IndexOf(buttonName)].Reset(); - CurrentTasMovie.SetFloatState(frame, buttonName, - FloatPatterns[controllerType.FloatControls.IndexOf(buttonName)].GetNextValue()); + FloatPatterns[ControllerType.FloatControls.IndexOf(buttonName)].Reset(); + CurrentTasMovie.SetFloatState(frame, buttonName, FloatPatterns[ControllerType.FloatControls.IndexOf(buttonName)].GetNextValue()); _patternPaint = true; } else + { _patternPaint = false; + } if (e.Clicks != 2 && !Settings.SingleClickFloatEdit) @@ -565,7 +647,9 @@ namespace BizHawk.Client.EmuHawk else // Double-click enters float editing mode { if (_floatEditColumn == buttonName && _floatEditRow == frame) + { floatEditRow = -1; + } else { CurrentTasMovie.ChangeLog.BeginNewBatch("Float Edit: " + frame); @@ -575,16 +659,19 @@ namespace BizHawk.Client.EmuHawk _floatEditYPos = e.Y; _floatBackupState = CurrentTasMovie.GetFloatState(_floatEditRow, _floatEditColumn); } + RefreshDialog(); } } // taseditor behavior if (!wasPaused) + { Mainform.UnpauseEmulator(); + } } } - else if (e.Button == System.Windows.Forms.MouseButtons.Right) + else if (e.Button == MouseButtons.Right) { if (TasView.CurrentCell.Column.Name == FrameColumnName && frame < CurrentTasMovie.InputLogLength) { @@ -601,7 +688,9 @@ namespace BizHawk.Client.EmuHawk } catch { } if (_rightClickControl && _rightClickShift) + { _rightClickFrame += _rightClickInput.Length; + } } else { @@ -609,26 +698,35 @@ namespace BizHawk.Client.EmuHawk _rightClickInput[0] = CurrentTasMovie.GetLogEntries()[frame]; _rightClickFrame = frame; } + _rightClickLastFrame = -1; if (_rightClickAlt || _rightClickControl || _rightClickShift) { JumpToGreenzone(); + // TODO: Turn off ChangeLog.IsRecording and handle the GeneralUndo here. string undoStepName = "Right-Click Edit:"; if (_rightClickShift) { undoStepName += " Extend Input"; if (_rightClickControl) + { undoStepName += ", Insert"; + } } else { if (_rightClickControl) + { undoStepName += " Copy"; + } else // _rightClickAlt + { undoStepName += " Move"; + } } + CurrentTasMovie.ChangeLog.BeginNewBatch(undoStepName); } } @@ -642,6 +740,7 @@ namespace BizHawk.Client.EmuHawk _startBoolDrawColumn = ""; _startFloatDrawColumn = ""; TasView.ReleaseCurrentCell(); + // Exit float editing if value was changed with cursor if (FloatEditingMode && _floatPaintState != CurrentTasMovie.GetFloatState(_floatEditRow, _floatEditColumn)) { @@ -686,10 +785,12 @@ namespace BizHawk.Client.EmuHawk _startSelectionDrag = false; } else + { ClearLeftMouseStates(); + } } - if (e.Button == System.Windows.Forms.MouseButtons.Right) + if (e.Button == MouseButtons.Right) { if (_rightClickFrame != -1) { @@ -712,12 +813,15 @@ namespace BizHawk.Client.EmuHawk _supressContextMenu = true; int notch = e.Delta / 120; if (notch > 1) + { notch *= 2; + } // warning: tastudio rewind hotkey/button logic is copypasted from here! if (Mainform.IsSeeking && !Mainform.EmulatorPaused) { Mainform.PauseOnFrame -= notch; + // that's a weird condition here, but for whatever reason it works best if (notch > 0 && Emulator.Frame >= Mainform.PauseOnFrame) { @@ -726,6 +830,7 @@ namespace BizHawk.Client.EmuHawk StopSeeking(); GoToFrame(Emulator.Frame - notch); } + RefreshDialog(); } else @@ -738,7 +843,9 @@ namespace BizHawk.Client.EmuHawk private void TasView_MouseDoubleClick(object sender, MouseEventArgs e) { if (TasView.CurrentCell.Column == null) + { return; + } if (e.Button == MouseButtons.Left) { @@ -815,19 +922,26 @@ namespace BizHawk.Client.EmuHawk if (FloatEditingMode && (Control.ModifierKeys == Keys.Control || Control.ModifierKeys == Keys.Shift)) { if (_selectionDragState) + { _extraFloatRows.Add(i); + } else + { _extraFloatRows.Remove(i); + } } } + SetSplicer(); } } - else if (_rightClickFrame != -1) { if (frame > CurrentTasMovie.InputLogLength - _rightClickInput.Length) + { frame = CurrentTasMovie.InputLogLength - _rightClickInput.Length; + } + if (_rightClickShift) { if (_rightClickControl) // Insert @@ -835,16 +949,20 @@ namespace BizHawk.Client.EmuHawk // If going backwards, delete! bool shouldInsert = true; if (startVal < _rightClickFrame) - { // Cloning to a previous frame makes no sense. + { + // Cloning to a previous frame makes no sense. startVal = _rightClickFrame - 1; } + if (startVal < _rightClickLastFrame) shouldInsert = false; if (shouldInsert) { for (int i = startVal + 1; i <= endVal; i++) + { CurrentTasMovie.InsertInput(i, _rightClickInput[(i - _rightClickFrame).Mod(_rightClickInput.Length)]); + } } else { @@ -856,7 +974,9 @@ namespace BizHawk.Client.EmuHawk else // Overwrite { for (int i = startVal; i <= endVal; i++) + { CurrentTasMovie.SetFrame(i, _rightClickInput[(i - _rightClickFrame).Mod(_rightClickInput.Length)]); + } } } else @@ -864,21 +984,29 @@ namespace BizHawk.Client.EmuHawk if (_rightClickControl) { for (int i = 0; i < _rightClickInput.Length; i++) // Re-set initial range, just to verify it's still there. + { CurrentTasMovie.SetFrame(_rightClickFrame + i, _rightClickInput[i]); + } if (_rightClickOverInput != null) // Restore overwritten input from previous movement { for (int i = 0; i < _rightClickOverInput.Length; i++) + { CurrentTasMovie.SetFrame(_rightClickLastFrame + i, _rightClickOverInput[i]); + } } else + { _rightClickOverInput = new string[_rightClickInput.Length]; + } _rightClickLastFrame = frame; // Set new restore log CurrentTasMovie.GetLogEntries().CopyTo(frame, _rightClickOverInput, 0, _rightClickOverInput.Length); for (int i = 0; i < _rightClickInput.Length; i++) // Place copied input + { CurrentTasMovie.SetFrame(frame + i, _rightClickInput[i]); + } } else if (_rightClickAlt) { @@ -886,18 +1014,26 @@ namespace BizHawk.Client.EmuHawk string[] shiftInput = new string[Math.Abs(shiftBy)]; int shiftFrom = frame; if (shiftBy < 0) + { shiftFrom = _rightClickFrame + _rightClickInput.Length; + } CurrentTasMovie.GetLogEntries().CopyTo(shiftFrom, shiftInput, 0, shiftInput.Length); int shiftTo = shiftFrom + (_rightClickInput.Length * Math.Sign(shiftBy)); for (int i = 0; i < shiftInput.Length; i++) + { CurrentTasMovie.SetFrame(shiftTo + i, shiftInput[i]); + } for (int i = 0; i < _rightClickInput.Length; i++) + { CurrentTasMovie.SetFrame(frame + i, _rightClickInput[i]); + } + _rightClickFrame = frame; } } + if (_rightClickAlt || _rightClickControl || _rightClickShift) { JumpToGreenzone(); @@ -905,6 +1041,7 @@ namespace BizHawk.Client.EmuHawk _supressContextMenu = true; } } + // Left-click else if (TasView.IsPaintDown && e.NewCell.RowIndex.HasValue && !string.IsNullOrEmpty(_startBoolDrawColumn)) { @@ -918,10 +1055,15 @@ namespace BizHawk.Client.EmuHawk if (_patternPaint && _boolPaintState) { if (CurrentTasMovie[frame].Lagged.HasValue && CurrentTasMovie[frame].Lagged.Value) + { setVal = CurrentTasMovie.BoolIsPressed(i - 1, _startBoolDrawColumn); + } else - setVal = BoolPatterns[controllerType.BoolButtons.IndexOf(_startBoolDrawColumn)].GetNextValue(); + { + setVal = BoolPatterns[ControllerType.BoolButtons.IndexOf(_startBoolDrawColumn)].GetNextValue(); + } } + CurrentTasMovie.SetBoolState(i, _startBoolDrawColumn, setVal); // Notice it uses new row, old column, you can only paint across a single column JumpToGreenzone(); } @@ -946,10 +1088,15 @@ namespace BizHawk.Client.EmuHawk if (_patternPaint) { if (CurrentTasMovie[frame].Lagged.HasValue && CurrentTasMovie[frame].Lagged.Value) + { setVal = CurrentTasMovie.GetFloatState(i - 1, _startFloatDrawColumn); + } else - setVal = FloatPatterns[controllerType.FloatControls.IndexOf(_startFloatDrawColumn)].GetNextValue(); + { + setVal = FloatPatterns[ControllerType.FloatControls.IndexOf(_startFloatDrawColumn)].GetNextValue(); + } } + CurrentTasMovie.SetFloatState(i, _startFloatDrawColumn, setVal); // Notice it uses new row, old column, you can only paint across a single column JumpToGreenzone(); } @@ -964,10 +1111,11 @@ namespace BizHawk.Client.EmuHawk Global.MovieSession.Movie.IsCountingRerecords = wasCountingRerecords; - if (mouseButtonHeld) + if (MouseButtonHeld) { TasView.MakeIndexVisible(TasView.CurrentCell.RowIndex.Value); // todo: limit scrolling speed } + RefreshTasView(); } @@ -979,8 +1127,9 @@ namespace BizHawk.Client.EmuHawk return; float value = _floatPaintState + increment; - Emulation.Common.ControllerDefinition.FloatRange range = Global.MovieSession.MovieControllerAdapter.Definition.FloatRanges + ControllerDefinition.FloatRange range = Global.MovieSession.MovieControllerAdapter.Definition.FloatRanges [Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(_floatEditColumn)]; + // Range for N64 Y axis has max -128 and min 127. That should probably be fixed in ControllerDefinition.cs. // SuuperW: I really don't think changing it would break anything, but adelikat isn't so sure. float rMax = range.Max; @@ -990,10 +1139,15 @@ namespace BizHawk.Client.EmuHawk rMax = range.Min; rMin = range.Max; } + if (value > rMax) + { value = rMax; + } else if (value < rMin) + { value = rMin; + } CurrentTasMovie.SetFloatState(_floatEditRow, _floatEditColumn, value); _floatTypedValue = value.ToString(); @@ -1012,53 +1166,68 @@ namespace BizHawk.Client.EmuHawk public void AnalogIncrementByOne() { if (FloatEditingMode) + { EditAnalogProgrammatically(new KeyEventArgs(Keys.Up)); + } } public void AnalogDecrementByOne() { if (FloatEditingMode) + { EditAnalogProgrammatically(new KeyEventArgs(Keys.Down)); + } } public void AnalogIncrementByTen() { if (FloatEditingMode) + { EditAnalogProgrammatically(new KeyEventArgs(Keys.Up | Keys.Shift)); + } } public void AnalogDecrementByTen() { if (FloatEditingMode) + { EditAnalogProgrammatically(new KeyEventArgs(Keys.Down | Keys.Shift)); + } } public void AnalogMax() { if (FloatEditingMode) + { EditAnalogProgrammatically(new KeyEventArgs(Keys.Right)); + } } public void AnalogMin() { if (FloatEditingMode) + { EditAnalogProgrammatically(new KeyEventArgs(Keys.Left)); + } } public void EditAnalogProgrammatically(KeyEventArgs e) { if (!FloatEditingMode) + { return; + } float value = CurrentTasMovie.GetFloatState(_floatEditRow, _floatEditColumn); float prev = value; string prevTyped = _floatTypedValue; - Emulation.Common.ControllerDefinition.FloatRange range = Global.MovieSession.MovieControllerAdapter.Definition.FloatRanges + ControllerDefinition.FloatRange range = Global.MovieSession.MovieControllerAdapter.Definition.FloatRanges [Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(_floatEditColumn)]; float rMax = range.Max; float rMin = range.Min; + // Range for N64 Y axis has max -128 and min 127. That should probably be fixed ControllerDefinition.cs, but I'll put a quick fix here anyway. if (rMax < rMin) { @@ -1095,31 +1264,48 @@ namespace BizHawk.Client.EmuHawk else if (e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) { if (curDigits >= maxDigits) + { _floatTypedValue = curMinus; + } + _floatTypedValue += e.KeyCode - Keys.D0; } else if (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) { if (curDigits >= maxDigits) + { _floatTypedValue = curMinus; + } + _floatTypedValue += e.KeyCode - Keys.NumPad0; } else if (e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Subtract) { if (_floatTypedValue.StartsWith("-")) + { _floatTypedValue = _floatTypedValue.Substring(1); + } else + { _floatTypedValue = "-" + _floatTypedValue; + } } else if (e.KeyCode == Keys.Back) { if (_floatTypedValue == "") // Very first key press is backspace? + { _floatTypedValue = value.ToString(); + } + _floatTypedValue = _floatTypedValue.Substring(0, _floatTypedValue.Length - 1); if (_floatTypedValue == "" || _floatTypedValue == "-") + { value = 0f; + } else + { value = Convert.ToSingle(_floatTypedValue); + } } else if (e.KeyCode == Keys.Enter) { @@ -1127,6 +1313,7 @@ namespace BizHawk.Client.EmuHawk { _floatEditYPos = -1; } + floatEditRow = -1; } else if (e.KeyCode == Keys.Escape) @@ -1135,6 +1322,7 @@ namespace BizHawk.Client.EmuHawk { _floatEditYPos = -1; } + if (_floatBackupState != _floatPaintState) { CurrentTasMovie.SetFloatState(_floatEditRow, _floatEditColumn, _floatBackupState); @@ -1142,24 +1330,37 @@ namespace BizHawk.Client.EmuHawk JumpToGreenzone(); DoTriggeredAutoRestoreIfNeeded(); } + floatEditRow = -1; } else { float changeBy = 0; if (e.KeyCode == Keys.Up) + { changeBy = 1; // We're assuming for now that ALL float controls should contain integers. + } else if (e.KeyCode == Keys.Down) + { changeBy = -1; + } + if (Control.ModifierKeys == Keys.Shift) + { changeBy *= 10; + } + value += changeBy; if (changeBy != 0) + { _floatTypedValue = value.ToString(); + } } if (!FloatEditingMode) + { CurrentTasMovie.ChangeLog.EndBatch(); + } else { if (_floatTypedValue == "") @@ -1175,9 +1376,14 @@ namespace BizHawk.Client.EmuHawk if (float.TryParse(_floatTypedValue, out value)) // String "-" can't be parsed. { if (value > rMax) + { value = rMax; + } else if (value < rMin) + { value = rMin; + } + _floatTypedValue = value.ToString(); CurrentTasMovie.SetFloatState(_floatEditRow, _floatEditColumn, value); } @@ -1198,6 +1404,7 @@ namespace BizHawk.Client.EmuHawk DoTriggeredAutoRestoreIfNeeded(); } } + RefreshDialog(); } @@ -1212,10 +1419,13 @@ namespace BizHawk.Client.EmuHawk GoToNextMarker(); } - if (FloatEditingMode && - e.KeyCode != Keys.Right && e.KeyCode != Keys.Left && - e.KeyCode != Keys.Up && e.KeyCode != Keys.Down) + if (FloatEditingMode && e.KeyCode != Keys.Right + && e.KeyCode != Keys.Left + && e.KeyCode != Keys.Up + && e.KeyCode != Keys.Down) + { EditAnalogProgrammatically(e); + } RefreshDialog(); } @@ -1226,8 +1436,11 @@ namespace BizHawk.Client.EmuHawk private void TasView_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) + { e.IsInputKey = true; + } } + #endregion } } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs index c481901f6c..30c4349282 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.MenuItems.cs @@ -25,7 +25,6 @@ namespace BizHawk.Client.EmuHawk SaveTASMenuItem.Enabled = !string.IsNullOrWhiteSpace(CurrentTasMovie.Filename) && (CurrentTasMovie.Filename != DefaultTasProjName()); - } private void RecentSubMenu_DropDownOpened(object sender, EventArgs e) @@ -92,12 +91,12 @@ namespace BizHawk.Client.EmuHawk } } - private bool _exiting = false; + private bool _exiting; private void SaveTas(object sender, EventArgs e) { - if (string.IsNullOrEmpty(CurrentTasMovie.Filename) || - CurrentTasMovie.Filename == DefaultTasProjName()) + if (string.IsNullOrEmpty(CurrentTasMovie.Filename) + || CurrentTasMovie.Filename == DefaultTasProjName()) { SaveAsTas(sender, e); } @@ -106,14 +105,17 @@ namespace BizHawk.Client.EmuHawk _autosaveTimer.Stop(); GlobalWin.Sound.StopSound(); MessageStatusLabel.Text = "Saving..."; - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; Update(); CurrentTasMovie.Save(); if (Settings.AutosaveInterval > 0) + { _autosaveTimer.Start(); + } + MessageStatusLabel.Text = CurrentTasMovie.Name + " saved."; Settings.RecentTas.Add(CurrentTasMovie.Filename); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; GlobalWin.Sound.StartSound(); } } @@ -123,7 +125,9 @@ namespace BizHawk.Client.EmuHawk { SaveTas(sender, e); if (Settings.BackupPerFileSave) + { SaveBackupMenuItem_Click(sender, e); + } } private void SaveAsTas(object sender, EventArgs e) @@ -147,17 +151,21 @@ namespace BizHawk.Client.EmuHawk { CurrentTasMovie.Filename = file.FullName; MessageStatusLabel.Text = "Saving..."; - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; Update(); CurrentTasMovie.Save(); Settings.RecentTas.Add(CurrentTasMovie.Filename); SetTextProperty(); MessageStatusLabel.Text = Path.GetFileName(CurrentTasMovie.Filename) + " saved."; - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } + // keep insisting if (Settings.AutosaveInterval > 0) + { _autosaveTimer.Start(); + } + GlobalWin.Sound.StartSound(); } @@ -166,13 +174,15 @@ namespace BizHawk.Client.EmuHawk { SaveAsTas(sender, e); if (Settings.BackupPerFileSave) + { SaveBackupMenuItem_Click(sender, e); + } } private void SaveBackupMenuItem_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(CurrentTasMovie.Filename) || - CurrentTasMovie.Filename == DefaultTasProjName()) + if (string.IsNullOrEmpty(CurrentTasMovie.Filename) + || CurrentTasMovie.Filename == DefaultTasProjName()) { SaveAsTas(sender, e); } @@ -181,14 +191,17 @@ namespace BizHawk.Client.EmuHawk _autosaveTimer.Stop(); GlobalWin.Sound.StopSound(); MessageStatusLabel.Text = "Saving..."; - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; Update(); CurrentTasMovie.SaveBackup(); if (Settings.AutosaveInterval > 0) + { _autosaveTimer.Start(); + } + MessageStatusLabel.Text = "Backup .tasproj saved to \"Movie backups\" path."; Settings.RecentTas.Add(CurrentTasMovie.Filename); - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; GlobalWin.Sound.StartSound(); } } @@ -198,31 +211,41 @@ namespace BizHawk.Client.EmuHawk _autosaveTimer.Stop(); var bk2 = CurrentTasMovie.ToBk2(copy: true, backup: true); MessageStatusLabel.Text = "Exporting to .bk2..."; - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; Update(); bk2.SaveBackup(); if (Settings.AutosaveInterval > 0) + { _autosaveTimer.Start(); + } + MessageStatusLabel.Text = "Backup .bk2 saved to \"Movie backups\" path."; - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } - private void saveSelectionToMacroToolStripMenuItem_Click(object sender, EventArgs e) + private void SaveSelectionToMacroMenuItem_Click(object sender, EventArgs e) { if (TasView.LastSelectedIndex == CurrentTasMovie.InputLogLength) + { TasView.SelectRow(CurrentTasMovie.InputLogLength, false); + } if (!TasView.AnyRowsSelected) + { return; + } MovieZone macro = new MovieZone(CurrentTasMovie, TasView.FirstSelectedIndex.Value, TasView.LastSelectedIndex.Value - TasView.FirstSelectedIndex.Value + 1); MacroInputTool.SaveMacroAs(macro); } - private void placeMacroAtSelectionToolStripMenuItem_Click(object sender, EventArgs e) + + private void PlaceMacroAtSelectionMenuItem_Click(object sender, EventArgs e) { if (!TasView.AnyRowsSelected) + { return; + } MovieZone macro = MacroInputTool.LoadMacro(); if (macro != null) @@ -232,7 +255,7 @@ namespace BizHawk.Client.EmuHawk } } - private void recentMacrosToolStripMenuItem_DropDownOpened(object sender, EventArgs e) + private void RecentMacrosMenuItem_DropDownOpened(object sender, EventArgs e) { recentMacrosToolStripMenuItem.DropDownItems.Clear(); recentMacrosToolStripMenuItem.DropDownItems.AddRange(Global.Config.RecentMacros.RecentMenu(DummyLoadMacro)); @@ -243,13 +266,16 @@ namespace BizHawk.Client.EmuHawk _autosaveTimer.Stop(); var bk2 = CurrentTasMovie.ToBk2(true); MessageStatusLabel.Text = "Exporting to .bk2..."; - this.Cursor = Cursors.WaitCursor; + Cursor = Cursors.WaitCursor; Update(); bk2.Save(); if (Settings.AutosaveInterval > 0) + { _autosaveTimer.Start(); + } + MessageStatusLabel.Text = bk2.Name + " exported."; - this.Cursor = Cursors.Default; + Cursor = Cursors.Default; } private void ExitMenuItem_Click(object sender, EventArgs e) @@ -313,30 +339,38 @@ namespace BizHawk.Client.EmuHawk private void UndoMenuItem_Click(object sender, EventArgs e) { if (CurrentTasMovie.ChangeLog.Undo() < Emulator.Frame) + { GoToFrame(CurrentTasMovie.ChangeLog.PreviousUndoFrame); + } else + { RefreshDialog(); + } // Currently I don't have a way to easily detect when CanUndo changes, so this button should be enabled always. - //UndoMenuItem.Enabled = CurrentTasMovie.ChangeLog.CanUndo; + // UndoMenuItem.Enabled = CurrentTasMovie.ChangeLog.CanUndo; RedoMenuItem.Enabled = CurrentTasMovie.ChangeLog.CanRedo; } private void RedoMenuItem_Click(object sender, EventArgs e) { if (CurrentTasMovie.ChangeLog.Redo() < Emulator.Frame) + { GoToFrame(CurrentTasMovie.ChangeLog.PreviousRedoFrame); + } else + { RefreshDialog(); + } - //UndoMenuItem.Enabled = CurrentTasMovie.ChangeLog.CanUndo; + // Currently I don't have a way to easily detect when CanUndo changes, so this button should be enabled always. + // UndoMenuItem.Enabled = CurrentTasMovie.ChangeLog.CanUndo; RedoMenuItem.Enabled = CurrentTasMovie.ChangeLog.CanRedo; } - private void showUndoHistoryToolStripMenuItem_Click(object sender, EventArgs e) + private void ShowUndoHistoryMenuItem_Click(object sender, EventArgs e) { - _undoForm = new UndoHistoryForm(this); - _undoForm.Owner = this; + _undoForm = new UndoHistoryForm(this) { Owner = this }; _undoForm.Show(); _undoForm.UpdateValues(); } @@ -360,13 +394,14 @@ namespace BizHawk.Client.EmuHawk var prevMarker = CurrentTasMovie.Markers.PreviousOrCurrent(TasView.LastSelectedIndex.Value); var nextMarker = CurrentTasMovie.Markers.Next(TasView.LastSelectedIndex.Value); - int prev = prevMarker != null ? prevMarker.Frame : 0; - int next = nextMarker != null ? nextMarker.Frame : CurrentTasMovie.InputLogLength; + int prev = prevMarker?.Frame ?? 0; + int next = nextMarker?.Frame ?? CurrentTasMovie.InputLogLength; for (int i = prev; i < next; i++) { TasView.SelectRow(i, true); } + SetSplicer(); RefreshTasView(); } @@ -379,6 +414,7 @@ namespace BizHawk.Client.EmuHawk { TasView.SelectRow(item.Frame, true); } + SetSplicer(); RefreshTasView(); } @@ -395,7 +431,10 @@ namespace BizHawk.Client.EmuHawk { var input = CurrentTasMovie.GetInputState(index); if (input == null) + { break; + } + _tasClipboard.Add(new TasClipboardEntry(index, input)); var lg = CurrentTasMovie.LogGeneratorInstance(); lg.SetSource(input); @@ -411,7 +450,6 @@ namespace BizHawk.Client.EmuHawk { // TODO: if highlighting 2 rows and pasting 3, only paste 2 of them // FCEUX Taseditor does't do this, but I think it is the expected behavior in editor programs - var wasPaused = Mainform.EmulatorPaused; // copypaste from PasteInsertMenuItem_Click! @@ -429,9 +467,13 @@ namespace BizHawk.Client.EmuHawk { var line = TasClipboardEntry.SetFromMnemonicStr(lines[i]); if (line == null) + { return; + } else + { _tasClipboard.Add(new TasClipboardEntry(i, line)); + } } var needsToRollback = TasView.FirstSelectedIndex < Emulator.Frame; @@ -469,9 +511,13 @@ namespace BizHawk.Client.EmuHawk { var line = TasClipboardEntry.SetFromMnemonicStr(lines[i]); if (line == null) + { return; + } else + { _tasClipboard.Add(new TasClipboardEntry(i, line)); + } } var needsToRollback = TasView.FirstSelectedIndex < Emulator.Frame; @@ -506,7 +552,10 @@ namespace BizHawk.Client.EmuHawk { var input = CurrentTasMovie.GetInputState(index); if (input == null) + { break; + } + _tasClipboard.Add(new TasClipboardEntry(index, input)); var lg = CurrentTasMovie.LogGeneratorInstance(); lg.SetSource(input); @@ -516,7 +565,7 @@ namespace BizHawk.Client.EmuHawk Clipboard.SetDataObject(sb.ToString()); CurrentTasMovie.RemoveFrames(list); SetSplicer(); - //TasView.DeselectAll(); feos: what if I want to continuously cut? + ////TasView.DeselectAll(); feos: what if I want to continuously cut? if (needsToRollback) { @@ -543,6 +592,7 @@ namespace BizHawk.Client.EmuHawk { CurrentTasMovie.ClearFrame(frame); } + CurrentTasMovie.ChangeLog.EndBatch(); if (needsToRollback) @@ -564,7 +614,8 @@ namespace BizHawk.Client.EmuHawk var needsToRollback = TasView.FirstSelectedIndex < Emulator.Frame; var rollBackFrame = TasView.FirstSelectedIndex.Value; if (rollBackFrame >= CurrentTasMovie.InputLogLength) - { // Cannot delete non-existant frames + { + // Cannot delete non-existant frames RefreshDialog(); return; } @@ -634,7 +685,7 @@ namespace BizHawk.Client.EmuHawk { int insertionFrame = TasView.AnyRowsSelected ? TasView.FirstSelectedIndex.Value : 0; - FramesPrompt framesPrompt = new FramesPrompt(); + var framesPrompt = new FramesPrompt(); DialogResult result = framesPrompt.ShowDialog(); if (result == DialogResult.OK) { @@ -669,8 +720,11 @@ namespace BizHawk.Client.EmuHawk { var result = MessageBox.Show("Are you sure you want to add more than 50 markers?", "Add markers", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (result != DialogResult.OK) + { return; + } } + foreach (var index in TasView.SelectedRows) { MarkerControl.AddMarker(false, index); @@ -689,6 +743,7 @@ namespace BizHawk.Client.EmuHawk { CurrentTasMovie.Markers.Remove(m); } + RefreshDialog(); } @@ -702,9 +757,10 @@ namespace BizHawk.Client.EmuHawk { if (!Emulator.DeterministicEmulation) { - if (MessageBox.Show("The emulator is not deterministic. It might fail even if the difference isn't enough to cause a desync.\nContinue with check?", "Not Deterministic", MessageBoxButtons.YesNo) - == System.Windows.Forms.DialogResult.No) + if (MessageBox.Show("The emulator is not deterministic. It might fail even if the difference isn't enough to cause a desync.\nContinue with check?", "Not Deterministic", MessageBoxButtons.YesNo) == DialogResult.No) + { return; + } } GoToFrame(0); @@ -727,7 +783,8 @@ namespace BizHawk.Client.EmuHawk lastState = Emulator.Frame; } - } while (Emulator.Frame < goToFrame); + } + while (Emulator.Frame < goToFrame); MessageBox.Show("Integrity Check passed"); } @@ -762,7 +819,9 @@ namespace BizHawk.Client.EmuHawk { int val = int.Parse(prompt.PromptText); if (val > 0) + { CurrentTasMovie.ChangeLog.MaxSteps = val; + } } } } @@ -854,7 +913,7 @@ namespace BizHawk.Client.EmuHawk TasView.InputPaintingMode = Settings.DrawInput ^= true; } - private void applyPatternToPaintedInputToolStripMenuItem_CheckedChanged(object sender, EventArgs e) + private void ApplyPatternToPaintedInputMenuItem_CheckedChanged(object sender, EventArgs e) { onlyOnAutoFireColumnsToolStripMenuItem.Enabled = applyPatternToPaintedInputToolStripMenuItem.Checked; } @@ -884,7 +943,7 @@ namespace BizHawk.Client.EmuHawk Settings.AutoRestoreOnMouseUpOnly ^= true; } - private void autoHoldToolStripMenuItem_CheckedChanged(object sender, EventArgs e) + private void AutoHoldMenuItem_CheckedChanged(object sender, EventArgs e) { if (autoHoldToolStripMenuItem.Checked) { @@ -892,10 +951,13 @@ namespace BizHawk.Client.EmuHawk customPatternToolStripMenuItem.Checked = false; if (!keepSetPatternsToolStripMenuItem.Checked) + { UpdateAutoFire(); + } } } - private void autoFireToolStripMenuItem_CheckedChanged(object sender, EventArgs e) + + private void AutoFireMenuItem_CheckedChanged(object sender, EventArgs e) { if (autoFireToolStripMenuItem.Checked) { @@ -903,10 +965,13 @@ namespace BizHawk.Client.EmuHawk customPatternToolStripMenuItem.Checked = false; if (!keepSetPatternsToolStripMenuItem.Checked) + { UpdateAutoFire(); + } } } - private void customPatternToolStripMenuItem_CheckedChanged(object sender, EventArgs e) + + private void CustomPatternMenuItem_CheckedChanged(object sender, EventArgs e) { if (customPatternToolStripMenuItem.Checked) { @@ -914,15 +979,17 @@ namespace BizHawk.Client.EmuHawk autoFireToolStripMenuItem.Checked = false; if (!keepSetPatternsToolStripMenuItem.Checked) + { UpdateAutoFire(); + } } } - private void setCustomsToolStripMenuItem_Click(object sender, EventArgs e) + + private void SetCustomsMenuItem_Click(object sender, EventArgs e) { // Exceptions in PatternsForm are not caught by the debugger, I have no idea why. // Exceptions in UndoForm are caught, which makes it weirder. - PatternsForm pForm = new PatternsForm(this); - pForm.Owner = this; + var pForm = new PatternsForm(this) { Owner = this }; pForm.Show(); } @@ -993,7 +1060,7 @@ namespace BizHawk.Client.EmuHawk hideWasLagFramesToolStripMenuItem.Checked = TasView.HideWasLagFrames; } - private void iconsToolStripMenuItem_DropDownOpened(object sender, EventArgs e) + private void IconsMenuItem_DropDownOpened(object sender, EventArgs e) { DenoteStatesWithIconsToolStripMenuItem.Checked = Settings.DenoteStatesWithIcons; DenoteStatesWithBGColorToolStripMenuItem.Checked = Settings.DenoteStatesWithBGColor; @@ -1001,7 +1068,7 @@ namespace BizHawk.Client.EmuHawk DenoteMarkersWithBGColorToolStripMenuItem.Checked = Settings.DenoteMarkersWithBGColor; } - private void followCursorToolStripMenuItem_DropDownOpened(object sender, EventArgs e) + private void FollowCursorMenuItem_DropDownOpened(object sender, EventArgs e) { alwaysScrollToolStripMenuItem.Checked = Settings.FollowCursorAlwaysScroll; scrollToViewToolStripMenuItem.Checked = false; @@ -1009,13 +1076,21 @@ namespace BizHawk.Client.EmuHawk scrollToBottomToolStripMenuItem.Checked = false; scrollToCenterToolStripMenuItem.Checked = false; if (TasView.ScrollMethod == "near") + { scrollToViewToolStripMenuItem.Checked = true; + } else if (TasView.ScrollMethod == "top") + { scrollToTopToolStripMenuItem.Checked = true; + } else if (TasView.ScrollMethod == "bottom") + { scrollToBottomToolStripMenuItem.Checked = true; + } else + { scrollToCenterToolStripMenuItem.Checked = true; + } } private void RotateMenuItem_Click(object sender, EventArgs e) @@ -1031,32 +1106,32 @@ namespace BizHawk.Client.EmuHawk RefreshDialog(); } - private void hideWasLagFramesToolStripMenuItem_Click(object sender, EventArgs e) + private void HideWasLagFramesMenuItem_Click(object sender, EventArgs e) { TasView.HideWasLagFrames ^= true; } - private void alwaysScrollToolStripMenuItem_Click(object sender, EventArgs e) + private void AlwaysScrollMenuItem_Click(object sender, EventArgs e) { TasView.AlwaysScroll = Settings.FollowCursorAlwaysScroll = alwaysScrollToolStripMenuItem.Checked; } - private void scrollToViewToolStripMenuItem_Click(object sender, EventArgs e) + private void ScrollToViewMenuItem_Click(object sender, EventArgs e) { TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "near"; } - private void scrollToTopToolStripMenuItem_Click(object sender, EventArgs e) + private void ScrollToTopMenuItem_Click(object sender, EventArgs e) { TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "top"; } - private void scrollToBottomToolStripMenuItem_Click(object sender, EventArgs e) + private void ScrollToBottomMenuItem_Click(object sender, EventArgs e) { TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "bottom"; } - private void scrollToCenterToolStripMenuItem_Click(object sender, EventArgs e) + private void ScrollToCenterMenuItem_Click(object sender, EventArgs e) { TasView.ScrollMethod = Settings.FollowCursorScrollMethod = "center"; } @@ -1085,18 +1160,19 @@ namespace BizHawk.Client.EmuHawk RefreshDialog(); } - private void wheelScrollSpeedToolStripMenuItem_Click(object sender, EventArgs e) + private void WheelScrollSpeedMenuItem_Click(object sender, EventArgs e) { - InputPrompt inputpromt = new InputPrompt(); - inputpromt.TextInputType = InputPrompt.InputType.Unsigned; - inputpromt.Message = "Frames per tick:"; - inputpromt.InitialValue = TasView.ScrollSpeed.ToString(); - if (inputpromt.ShowDialog() == System.Windows.Forms.DialogResult.OK) + var inputpromt = new InputPrompt + { + TextInputType = InputPrompt.InputType.Unsigned, + Message = "Frames per tick:", + InitialValue = TasView.ScrollSpeed.ToString() + }; + if (inputpromt.ShowDialog() == DialogResult.OK) { TasView.ScrollSpeed = int.Parse(inputpromt.PromptText); Settings.ScrollSpeed = TasView.ScrollSpeed; } - } #endregion @@ -1117,7 +1193,6 @@ namespace BizHawk.Client.EmuHawk { playerMenus[i] = new ToolStripMenuItem("Player " + i); } - int player = 0; foreach (InputRoll.RollColumn column in columns) { @@ -1140,6 +1215,7 @@ namespace BizHawk.Client.EmuHawk (sender.OwnerItem as ToolStripMenuItem).ShowDropDown(); }; + int player; if (column.Name.StartsWith("P") && column.Name.Length > 1 && char.IsNumber(column.Name, 1)) { player = int.Parse(column.Name[1].ToString()); @@ -1153,14 +1229,18 @@ namespace BizHawk.Client.EmuHawk } for (int i = 1; i < playerMenus.Length; i++) + { ColumnsSubMenu.DropDownItems.Add(playerMenus[i]); + } ColumnsSubMenu.DropDownItems.Add(new ToolStripSeparator()); for (int i = 1; i < playerMenus.Length; i++) { - ToolStripMenuItem item = new ToolStripMenuItem("Show Player " + i); - item.CheckOnClick = true; - item.Checked = true; + var item = new ToolStripMenuItem("Show Player " + i) + { + CheckOnClick = true, + Checked = true + }; int dummyInt = i; ToolStripMenuItem dummyObject = playerMenus[i]; @@ -1217,7 +1297,6 @@ namespace BizHawk.Client.EmuHawk TruncateContextMenuItem.Enabled = TasView.AnyRowsSelected; - StartNewProjectFromNowMenuItem.Visible = TasView.SelectedRows.Count() == 1 && TasView.SelectedRows.Contains(Emulator.Frame) @@ -1228,7 +1307,7 @@ namespace BizHawk.Client.EmuHawk && SaveRamEmulator != null && !CurrentTasMovie.StartsFromSavestate; - StartFromNowSeparator.Visible =StartNewProjectFromNowMenuItem.Visible || StartANewProjectFromSaveRamMenuItem.Visible; + StartFromNowSeparator.Visible = StartNewProjectFromNowMenuItem.Visible || StartANewProjectFromSaveRamMenuItem.Visible; RemoveMarkersContextMenuItem.Enabled = CurrentTasMovie.Markers.Any(m => TasView.SelectedRows.Contains(m.Frame)); // Disable the option to remove markers if no markers are selected (FCEUX does this). CancelSeekContextMenuItem.Enabled = Mainform.PauseOnFrame.HasValue; BranchContextMenuItem.Visible = TasView.CurrentCell.RowIndex == Emulator.Frame; diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs index 368e164daf..7514d05f9c 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.Navigation.cs @@ -1,7 +1,4 @@ -using System.Linq; -using System.IO; - -using BizHawk.Client.Common; +using BizHawk.Client.Common; namespace BizHawk.Client.EmuHawk { @@ -18,12 +15,13 @@ namespace BizHawk.Client.EmuHawk if (frame <= Emulator.Frame) { - if ((Mainform.EmulatorPaused || !Mainform.IsSeeking) && - !CurrentTasMovie.LastPositionStable) + if ((Mainform.EmulatorPaused || !Mainform.IsSeeking) + && !CurrentTasMovie.LastPositionStable) { LastPositionFrame = Emulator.Frame; CurrentTasMovie.LastPositionStable = true; // until new frame is emulated } + GoToFrame(frame); } } @@ -51,7 +49,9 @@ namespace BizHawk.Client.EmuHawk bool wasPaused = Mainform.EmulatorPaused; Mainform.FrameAdvance(); if (!wasPaused) + { Mainform.UnpauseEmulator(); + } } else { @@ -59,7 +59,9 @@ namespace BizHawk.Client.EmuHawk int lastState = CurrentTasMovie.TasStateManager.GetStateClosestToFrame(frame).Key; // Simply getting the last state doesn't work if that state is the frame. [dispaly isn't saved in the state, need to emulate to frame] if (lastState > Emulator.Frame) + { LoadState(CurrentTasMovie.TasStateManager[lastState]); // STATE ACCESS + } StartSeeking(frame); } @@ -87,7 +89,7 @@ namespace BizHawk.Client.EmuHawk if (Emulator.Frame > 0) { var prevMarker = CurrentTasMovie.Markers.Previous(Emulator.Frame); - var prev = prevMarker != null ? prevMarker.Frame : 0; + var prev = prevMarker?.Frame ?? 0; GoToFrame(prev); } } @@ -95,7 +97,7 @@ namespace BizHawk.Client.EmuHawk public void GoToNextMarker() { var nextMarker = CurrentTasMovie.Markers.Next(Emulator.Frame); - var next = nextMarker != null ? nextMarker.Frame : CurrentTasMovie.InputLogLength - 1; + var next = nextMarker?.Frame ?? CurrentTasMovie.InputLogLength - 1; GoToFrame(next); } @@ -110,7 +112,9 @@ namespace BizHawk.Client.EmuHawk public void SetVisibleIndex(int? indexThatMustBeVisible = null) { if (!indexThatMustBeVisible.HasValue) + { indexThatMustBeVisible = Emulator.Frame; + } TasView.ScrollToIndex(indexThatMustBeVisible.Value); } @@ -118,7 +122,9 @@ namespace BizHawk.Client.EmuHawk private void MaybeFollowCursor() { if (TasPlaybackBox.FollowCursor) + { SetVisibleIndex(); + } } } } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs index d5e3f5a648..524d4df4a6 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudio.cs @@ -8,6 +8,7 @@ using System.ComponentModel; using BizHawk.Emulation.Common; using BizHawk.Emulation.Common.IEmulatorExtensions; +using BizHawk.Emulation.Cores.Nintendo.SNES; using BizHawk.Client.Common; using BizHawk.Client.Common.MovieConversionExtensions; @@ -20,11 +21,12 @@ namespace BizHawk.Client.EmuHawk public partial class TAStudio : ToolFormBase, IToolFormAutoConfig, IControlMainform { // TODO: UI flow that conveniently allows to start from savestate - public TasMovie CurrentTasMovie { get { return Global.MovieSession.Movie as TasMovie; } } - public MainForm Mainform { get { return GlobalWin.MainForm; } } + public TasMovie CurrentTasMovie => Global.MovieSession.Movie as TasMovie; + private MainForm Mainform => GlobalWin.MainForm; + public bool IsInMenuLoop { get; private set; } - public string statesPath { get { - return PathManager.MakeAbsolutePath(Global.Config.PathEntries["Global", "TAStudio states"].Path, null); } } + public string StatesPath => PathManager.MakeAbsolutePath(Global.Config.PathEntries["Global", "TAStudio states"].Path, null); + private readonly List _tasClipboard = new List(); private const string CursorColumnName = "CursorColumn"; private const string FrameColumnName = "FrameColumn"; @@ -34,16 +36,16 @@ namespace BizHawk.Client.EmuHawk private Timer _autosaveTimer; /// - /// Separates "restore last position" logic from seeking caused by navigation. + /// Gets or sets a value that separates "restore last position" logic from seeking caused by navigation. /// TASEditor never kills LastPositionFrame, and it only pauses on it, if it hasn't been greenzoned beforehand and middle mouse button was pressed. /// - public int LastPositionFrame { get; set; } + public int LastPositionFrame { get; private set; } private Dictionary GenerateColumnNames() { var lg = Global.MovieSession.LogGeneratorInstance(); lg.SetSource(Global.MovieSession.MovieControllerAdapter); - return (lg as Bk2LogEntryGenerator).Map(); + return ((Bk2LogEntryGenerator)lg).Map(); } [ConfigPersist] @@ -68,6 +70,7 @@ namespace BizHawk.Client.EmuHawk AutosaveAsBackupFile = false; BackupPerFileSave = false; SingleClickFloatEdit = false; + // default to taseditor fashion DenoteStatesWithIcons = false; DenoteStatesWithBGColor = true; @@ -75,7 +78,7 @@ namespace BizHawk.Client.EmuHawk DenoteMarkersWithBGColor = true; } - public RecentFiles RecentTas { get; set; } + public RecentFiles RecentTas { get; } public bool DrawInput { get; set; } public bool AutoPause { get; set; } public bool AutoRestoreLastPosition { get; set; } @@ -100,7 +103,7 @@ namespace BizHawk.Client.EmuHawk public int BranchMarkerSplitDistance { get; set; } } - #region "Initializing" + #region Initializing public TAStudio() { @@ -109,7 +112,7 @@ namespace BizHawk.Client.EmuHawk InitializeSeekWorker(); // TODO: show this at all times or hide it when saving is done? - this.SavingProgressBar.Visible = false; + SavingProgressBar.Visible = false; WantsToControlStopMovie = true; WantsToControlRestartMovie = true; @@ -130,24 +133,36 @@ namespace BizHawk.Client.EmuHawk private void AutosaveTimerEventProcessor(object sender, EventArgs e) { if (CurrentTasMovie == null) + { return; + } if (!CurrentTasMovie.Changes || Settings.AutosaveInterval == 0) + { return; + } if (Settings.AutosaveAsBackupFile) { if (Settings.AutosaveAsBk2) + { SaveBk2BackupMenuItem_Click(sender, e); + } else + { SaveBackupMenuItem_Click(sender, e); + } } else { if (Settings.AutosaveAsBk2) + { ToBk2MenuItem_Click(sender, e); + } else + { SaveTas(sender, e); + } } } @@ -159,15 +174,17 @@ namespace BizHawk.Client.EmuHawk _seekBackgroundWorker = null; // Idk if this line is even useful. } - _seekBackgroundWorker = new BackgroundWorker(); - _seekBackgroundWorker.WorkerReportsProgress = true; - _seekBackgroundWorker.WorkerSupportsCancellation = true; + _seekBackgroundWorker = new BackgroundWorker + { + WorkerReportsProgress = true, + WorkerSupportsCancellation = true + }; _seekBackgroundWorker.DoWork += (s, e) => { - this.Invoke(() => this.MessageStatusLabel.Text = "Seeking..."); - this.Invoke(() => this.SavingProgressBar.Visible = true); - for ( ; ; ) + this.Invoke(() => MessageStatusLabel.Text = "Seeking..."); + this.Invoke(() => SavingProgressBar.Visible = true); + for (;;) { if (_seekBackgroundWorker.CancellationPending || !this.IsHandleCreated) { @@ -180,9 +197,14 @@ namespace BizHawk.Client.EmuHawk double progress = 0; if (diff != 0 && unit != 0) + { progress = (double)100d / unit * diff; + } + if (progress < 0) + { progress = 0; + } _seekBackgroundWorker.ReportProgress((int)progress); System.Threading.Thread.Sleep(1); @@ -191,18 +213,18 @@ namespace BizHawk.Client.EmuHawk _seekBackgroundWorker.ProgressChanged += (s, e) => { - this.Invoke(() => this.SavingProgressBar.Value = e.ProgressPercentage); + this.Invoke(() => SavingProgressBar.Value = e.ProgressPercentage); }; _seekBackgroundWorker.RunWorkerCompleted += (s, e) => { - this.Invoke(() => this.SavingProgressBar.Visible = false); - this.Invoke(() => this.MessageStatusLabel.Text = ""); + this.Invoke(() => SavingProgressBar.Visible = false); + this.Invoke(() => MessageStatusLabel.Text = ""); InitializeSeekWorker(); // Required, or it will error when trying to report progress again. }; } - private bool _initialized = false; + private bool _initialized; private void Tastudio_Load(object sender, EventArgs e) { if (!InitializeOnLoad()) @@ -279,9 +301,9 @@ namespace BizHawk.Client.EmuHawk Mainform.PauseEmulator(); // Start Scenario 0: bsnes in performance mode (copied from RecordMovieMenuItem_Click()) - if (Emulator is BizHawk.Emulation.Cores.Nintendo.SNES.LibsnesCore) + if (Emulator is LibsnesCore) { - var snes = (BizHawk.Emulation.Cores.Nintendo.SNES.LibsnesCore)Emulator; + var snes = (LibsnesCore)Emulator; if (snes.CurrentProfile == "Performance") { var box = new CustomControls.MsgBox( @@ -362,7 +384,10 @@ namespace BizHawk.Client.EmuHawk private void SetTasMovieCallbacks(TasMovie movie = null) { if (movie == null) + { movie = CurrentTasMovie; + } + movie.ClientSettingsForSave = ClientSettingsForSave; movie.GetClientSettingsOnLoad = GetClientSettingsOnLoad; } @@ -384,13 +409,13 @@ namespace BizHawk.Client.EmuHawk AddColumn(FrameColumnName, "Frame#", 68); var columnNames = GenerateColumnNames(); - InputRoll.RollColumn.InputType type; - int digits = 1; foreach (var kvp in columnNames) { + InputRoll.RollColumn.InputType type; + int digits; if (Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.Contains(kvp.Key)) { - Emulation.Common.ControllerDefinition.FloatRange range = Global.MovieSession.MovieControllerAdapter.Definition.FloatRanges + ControllerDefinition.FloatRange range = Global.MovieSession.MovieControllerAdapter.Definition.FloatRanges [Global.MovieSession.MovieControllerAdapter.Definition.FloatControls.IndexOf(kvp.Key)]; type = InputRoll.RollColumn.InputType.Float; digits = Math.Max(kvp.Value.Length, range.MaxDigits()); @@ -400,21 +425,21 @@ namespace BizHawk.Client.EmuHawk type = InputRoll.RollColumn.InputType.Boolean; digits = kvp.Value.Length; } + AddColumn(kvp.Key, kvp.Value, (digits * 6) + 14, type); // magic numbers reused in EditBranchTextPopUp() } var columnsToHide = TasView.AllColumns .Where(c => // todo: make a proper user editable list? - c.Name == "Power" || - c.Name == "Reset" || - c.Name == "Light Sensor" || - c.Name == "Open" || - c.Name == "Close" || - c.Name == "Disc Select" || - c.Name.StartsWith("Tilt") || - c.Name.StartsWith("Key ") - ); + c.Name == "Power" + || c.Name == "Reset" + || c.Name == "Light Sensor" + || c.Name == "Open" + || c.Name == "Close" + || c.Name == "Disc Select" + || c.Name.StartsWith("Tilt") + || c.Name.StartsWith("Key ")); foreach (var column in columnsToHide) { @@ -428,34 +453,39 @@ namespace BizHawk.Client.EmuHawk int fStart = 0; if (BoolPatterns == null) { - BoolPatterns = new AutoPatternBool[controllerType.BoolButtons.Count + 2]; - FloatPatterns = new AutoPatternFloat[controllerType.FloatControls.Count + 2]; + BoolPatterns = new AutoPatternBool[ControllerType.BoolButtons.Count + 2]; + FloatPatterns = new AutoPatternFloat[ControllerType.FloatControls.Count + 2]; } else { bStart = BoolPatterns.Length - 2; fStart = FloatPatterns.Length - 2; - Array.Resize(ref BoolPatterns, controllerType.BoolButtons.Count + 2); - Array.Resize(ref FloatPatterns, controllerType.FloatControls.Count + 2); + Array.Resize(ref BoolPatterns, ControllerType.BoolButtons.Count + 2); + Array.Resize(ref FloatPatterns, ControllerType.FloatControls.Count + 2); } for (int i = bStart; i < BoolPatterns.Length - 2; i++) + { BoolPatterns[i] = new AutoPatternBool(1, 1); + } BoolPatterns[BoolPatterns.Length - 2] = new AutoPatternBool(1, 0); BoolPatterns[BoolPatterns.Length - 1] = new AutoPatternBool( Global.Config.AutofireOn, Global.Config.AutofireOff); for (int i = fStart; i < FloatPatterns.Length - 2; i++) - FloatPatterns[i] = new AutoPatternFloat(new float[] { 1f }); - FloatPatterns[FloatPatterns.Length - 2] = new AutoPatternFloat(new float[] { 1f }); + { + FloatPatterns[i] = new AutoPatternFloat(new[] { 1f }); + } + + FloatPatterns[FloatPatterns.Length - 2] = new AutoPatternFloat(new[] { 1f }); FloatPatterns[FloatPatterns.Length - 1] = new AutoPatternFloat( 1f, Global.Config.AutofireOn, 0f, Global.Config.AutofireOff); SetUpToolStripColumns(); } - public void AddColumn(string columnName, string columnText, int columnWidth, InputRoll.RollColumn.InputType columnType = InputRoll.RollColumn.InputType.Boolean) + private void AddColumn(string columnName, string columnText, int columnWidth, InputRoll.RollColumn.InputType columnType = InputRoll.RollColumn.InputType.Boolean) { if (TasView.AllColumns[columnName] == null) { @@ -487,7 +517,7 @@ namespace BizHawk.Client.EmuHawk #endregion - #region "Loading" + #region Loading private void ConvertCurrentMovieToTasproj() { @@ -511,23 +541,35 @@ namespace BizHawk.Client.EmuHawk newMovie.Filename = file.FullName; if (!HandleMovieLoadStuff(newMovie)) + { return false; + } Settings.RecentTas.Add(newMovie.Filename); // only add if it did load if (startsFromSavestate) + { GoToFrame(0); + } else if (gotoFrame > 0) + { GoToFrame(gotoFrame); + } else + { GoToFrame(CurrentTasMovie.Session.CurrentFrame); + } if (TasView.AllColumns.Count == 0 || file.Extension != "." + TasMovie.Extension) + { SetUpColumns(); + } else + { SetUpToolStripColumns(); + } - CurrentTasMovie.PropertyChanged += new PropertyChangedEventHandler(this.TasMovie_OnPropertyChanged); + CurrentTasMovie.PropertyChanged += TasMovie_OnPropertyChanged; CurrentTasMovie.CurrentBranch = CurrentTasMovie.Session.CurrentBranch; BookMarkControl.UpdateTextColumnWidth(); @@ -545,16 +587,17 @@ namespace BizHawk.Client.EmuHawk if (AskSaveChanges()) { Global.MovieSession.Movie = new TasMovie(false, _seekBackgroundWorker); - var stateManager = (Global.MovieSession.Movie as TasMovie).TasStateManager; + var stateManager = ((TasMovie)Global.MovieSession.Movie).TasStateManager; stateManager.MountWriteAccess(); stateManager.InvalidateCallback = GreenzoneInvalidated; - CurrentTasMovie.PropertyChanged += new PropertyChangedEventHandler(this.TasMovie_OnPropertyChanged); + CurrentTasMovie.PropertyChanged += TasMovie_OnPropertyChanged; CurrentTasMovie.Filename = DefaultTasProjName(); // TODO don't do this, take over any mainform actions that can crash without a filename CurrentTasMovie.PopulateWithDefaultHeaderValues(); SetTasMovieCallbacks(); CurrentTasMovie.ClearChanges(); // Don't ask to save changes here. HandleMovieLoadStuff(); CurrentTasMovie.TasStateManager.Capture(); // Capture frame 0 always. + // clear all selections TasView.DeselectAll(); BookMarkControl.Restart(); @@ -580,7 +623,9 @@ namespace BizHawk.Client.EmuHawk } if (!result) + { return false; + } WantsToControlStopMovie = true; @@ -598,7 +643,9 @@ namespace BizHawk.Client.EmuHawk _initializing = true; if (movie == null) + { movie = CurrentTasMovie; + } SetTasMovieCallbacks(movie as TasMovie); @@ -609,7 +656,7 @@ namespace BizHawk.Client.EmuHawk BookMarkControl.UpdateTextColumnWidth(); } - TastudioPlayMode(); + TastudioPlayMode(); _initializing = false; @@ -619,20 +666,23 @@ namespace BizHawk.Client.EmuHawk private void DummyLoadProject(string path) { if (AskSaveChanges()) + { LoadFile(new FileInfo(path)); + } } private void DummyLoadMacro(string path) { if (!TasView.AnyRowsSelected) - return; - - MovieZone loadZone = new MovieZone(path); - if (loadZone != null) { - loadZone.Start = TasView.FirstSelectedIndex.Value; - loadZone.PlaceZone(CurrentTasMovie); + return; } + + MovieZone loadZone = new MovieZone(path) + { + Start = TasView.FirstSelectedIndex.Value + }; + loadZone.PlaceZone(CurrentTasMovie); } private void SetColumnsFromCurrentStickies() @@ -672,9 +722,10 @@ namespace BizHawk.Client.EmuHawk Mainform.TakeBackControl(); Global.Config.MovieEndAction = _originalEndAction; Mainform.SetMainformMovieInfo(); + // Do not keep TAStudio's disk save states. - //if (Directory.Exists(statesPath)) Directory.Delete(statesPath, true); - //TODO - do we need to dispose something here instead? + // if (Directory.Exists(statesPath)) Directory.Delete(statesPath, true); + // TODO - do we need to dispose something here instead? } /// @@ -690,7 +741,6 @@ namespace BizHawk.Client.EmuHawk /// /// Used for things like SaveFile dialogs to suggest a name to the user /// - /// private static string SuggestedTasProjName() { return Path.Combine( @@ -706,7 +756,7 @@ namespace BizHawk.Client.EmuHawk text += " - " + CurrentTasMovie.Name + (CurrentTasMovie.Changes ? "*" : ""); } - if (this.InvokeRequired) + if (InvokeRequired) { this.Invoke(() => Text = text); } @@ -724,32 +774,39 @@ namespace BizHawk.Client.EmuHawk public void RefreshDialog(bool refreshTasView = true) { if (_exiting) + { return; + } if (refreshTasView) + { RefreshTasView(); + } - if (MarkerControl != null) - MarkerControl.UpdateValues(); + MarkerControl?.UpdateValues(); - if (BookMarkControl != null) - BookMarkControl.UpdateValues(); + BookMarkControl?.UpdateValues(); if (_undoForm != null && !_undoForm.IsDisposed) + { _undoForm.UpdateValues(); + } } private void RefreshTasView() { CurrentTasMovie.UseInputCache = true; if (TasView.RowCount != CurrentTasMovie.InputLogLength + 1) + { TasView.RowCount = CurrentTasMovie.InputLogLength + 1; + } + TasView.Refresh(); CurrentTasMovie.FlushInputCache(); CurrentTasMovie.UseInputCache = false; - lastRefresh = Emulator.Frame; + _lastRefresh = Emulator.Frame; } private void DoAutoRestore() @@ -768,9 +825,9 @@ namespace BizHawk.Client.EmuHawk // this happens when we're holding the left button while unpaused - view scrolls down, new input gets drawn, seek pauses Mainform.UnpauseEmulator(); } + _autoRestorePaused = null; } - //_autoRestoreFrame = null; } private void StartAtNearestFrameAndEmulate(int frame, bool fromLua, bool fromRewinding) @@ -790,25 +847,31 @@ namespace BizHawk.Client.EmuHawk { bool wasPaused = Mainform.EmulatorPaused; - //why not use this? because I'm not letting the form freely run. it all has to be under this loop. - //i could use this and then poll StepRunLoop_Core() repeatedly, but.. that's basically what I'm doing - //PauseOnFrame = frame; + // why not use this? because I'm not letting the form freely run. it all has to be under this loop. + // i could use this and then poll StepRunLoop_Core() repeatedly, but.. that's basically what I'm doing + // PauseOnFrame = frame; - //can't re-enter lua while doing this + // can't re-enter lua while doing this Mainform.SuppressLua = true; while (Emulator.Frame != frame) + { Mainform.SeekFrameAdvance(); + } + Mainform.SuppressLua = false; - if(!wasPaused) Mainform.UnpauseEmulator(); + if (!wasPaused) + { + Mainform.UnpauseEmulator(); + } - //lua botting users will want to re-activate record mode automatically -- it should be like nothing ever happened + // lua botting users will want to re-activate record mode automatically -- it should be like nothing ever happened if (WasRecording) { TastudioRecordMode(); } - //now the next section won't happen since we're at the right spot + // now the next section won't happen since we're at the right spot } // frame == Emulator.Frame when frame == 0 @@ -820,9 +883,9 @@ namespace BizHawk.Client.EmuHawk } else { - //GUI users may want to be protected from clobbering their video when skipping around... - //well, users who are rewinding arent. (that gets done through the seeking system in the call above) - //users who are clicking around.. I dont know. + // GUI users may want to be protected from clobbering their video when skipping around... + // well, users who are rewinding arent. (that gets done through the seeking system in the call above) + // users who are clicking around.. I dont know. } } } @@ -937,7 +1000,9 @@ namespace BizHawk.Client.EmuHawk private void Tastudio_Closing(object sender, FormClosingEventArgs e) { if (!_initialized) + { return; + } _exiting = true; @@ -953,12 +1018,11 @@ namespace BizHawk.Client.EmuHawk _exiting = false; } - if (_undoForm != null) - _undoForm.Close(); + _undoForm?.Close(); } /// - /// This method is called everytime the Changes property is toggled on a TasMovie instance. + /// This method is called every time the Changes property is toggled on a instance. /// private void TasMovie_OnPropertyChanged(object sender, PropertyChangedEventArgs e) { @@ -969,10 +1033,13 @@ namespace BizHawk.Client.EmuHawk { e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Copy : DragDropEffects.None; } + private void TAStudio_DragDrop(object sender, DragEventArgs e) { if (!AskSaveChanges()) + { return; + } var filePaths = (string[])e.Data.GetData(DataFormats.FileDrop); if (Path.GetExtension(filePaths[0]) == "." + TasMovie.Extension) @@ -992,9 +1059,9 @@ namespace BizHawk.Client.EmuHawk protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { - if (keyData == Keys.Tab || - keyData == (Keys.Shift | Keys.Tab) || - keyData == Keys.Space) + if (keyData == Keys.Tab + || keyData == (Keys.Shift | Keys.Tab) + || keyData == Keys.Space) { return true; } @@ -1012,7 +1079,8 @@ namespace BizHawk.Client.EmuHawk if (lagLog.WasLagged.HasValue) { if (lagLog.WasLagged.Value && !isLag) - { // Deleting this frame requires rewinding a frame. + { + // Deleting this frame requires rewinding a frame. CurrentTasMovie.ChangeLog.AddInputBind(Emulator.Frame - 1, true, "Bind Input; Delete " + (Emulator.Frame - 1)); bool wasRecording = CurrentTasMovie.ChangeLog.IsRecording; CurrentTasMovie.ChangeLog.IsRecording = false; @@ -1059,8 +1127,7 @@ namespace BizHawk.Client.EmuHawk private void TasView_CellDropped(object sender, InputRoll.CellEventArgs e) { - if (e.NewCell != null && e.NewCell.RowIndex.HasValue && - !CurrentTasMovie.Markers.IsMarker(e.NewCell.RowIndex.Value)) + if (e.NewCell?.RowIndex != null && !CurrentTasMovie.Markers.IsMarker(e.NewCell.RowIndex.Value)) { var currentMarker = CurrentTasMovie.Markers.Single(m => m.Frame == e.OldCell.RowIndex.Value); int newFrame = e.NewCell.RowIndex.Value; diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudioClipboard.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudioClipboard.cs index a42dbaf4bf..3bae7f5d49 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudioClipboard.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/TAStudioClipboard.cs @@ -1,4 +1,7 @@ -using BizHawk.Emulation.Common; +using System; +using System.Windows.Forms; + +using BizHawk.Emulation.Common; using BizHawk.Client.Common; namespace BizHawk.Client.EmuHawk @@ -39,9 +42,9 @@ namespace BizHawk.Client.EmuHawk return lg; } - catch (System.Exception) + catch (Exception) { - System.Windows.Forms.MessageBox.Show("Invalid mnemonic string: " + inputLogEntry, "Paste Input failed!"); + MessageBox.Show("Invalid mnemonic string: " + inputLogEntry, "Paste Input failed!"); return null; } } diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.Designer.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.Designer.cs index ad6a57aa75..2e4168040e 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.Designer.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.Designer.cs @@ -95,14 +95,14 @@ this.undoHereToolStripMenuItem.Name = "undoHereToolStripMenuItem"; this.undoHereToolStripMenuItem.Size = new System.Drawing.Size(208, 22); this.undoHereToolStripMenuItem.Text = "Undo To Selection"; - this.undoHereToolStripMenuItem.Click += new System.EventHandler(this.undoHereToolStripMenuItem_Click); + this.undoHereToolStripMenuItem.Click += new System.EventHandler(this.UndoHereMenuItem_Click); // // redoHereToolStripMenuItem // this.redoHereToolStripMenuItem.Name = "redoHereToolStripMenuItem"; this.redoHereToolStripMenuItem.Size = new System.Drawing.Size(208, 22); this.redoHereToolStripMenuItem.Text = "Redo To Selection"; - this.redoHereToolStripMenuItem.Click += new System.EventHandler(this.redoHereToolStripMenuItem_Click); + this.redoHereToolStripMenuItem.Click += new System.EventHandler(this.RedoHereMenuItem_Click); // // sepToolStripMenuItem // @@ -114,7 +114,7 @@ this.clearHistoryToHereToolStripMenuItem.Name = "clearHistoryToHereToolStripMenuItem"; this.clearHistoryToHereToolStripMenuItem.Size = new System.Drawing.Size(208, 22); this.clearHistoryToHereToolStripMenuItem.Text = "Clear History To Selection"; - this.clearHistoryToHereToolStripMenuItem.Click += new System.EventHandler(this.clearHistoryToHereToolStripMenuItem_Click); + this.clearHistoryToHereToolStripMenuItem.Click += new System.EventHandler(this.ClearHistoryToHereMenuItem_Click); // // AutoScrollCheck // diff --git a/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.cs b/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.cs index 692f8ef1b8..5b37c6f46d 100644 --- a/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.cs +++ b/BizHawk.Client.EmuHawk/tools/TAStudio/UndoHistoryForm.cs @@ -1,150 +1,171 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; -using System.Linq; -using System.Text; using System.Windows.Forms; +using BizHawk.Client.Common; namespace BizHawk.Client.EmuHawk { public partial class UndoHistoryForm : Form { - private TAStudio tastudio; + private readonly TAStudio _tastudio; + private string _lastUndoAction; + private TasMovieChangeLog Log => _tastudio.CurrentTasMovie.ChangeLog; public UndoHistoryForm(TAStudio owner) { InitializeComponent(); - tastudio = owner; + _tastudio = owner; HistoryView.QueryItemText += HistoryView_QueryItemText; HistoryView.QueryItemBkColor += HistoryView_QueryItemBkColor; HistoryView.Columns[1].Width = 280; - MaxStepsNum.Value = log.MaxSteps; - } - - private Common.TasMovieChangeLog log - { - get { return tastudio.CurrentTasMovie.ChangeLog; } + MaxStepsNum.Value = Log.MaxSteps; } private void HistoryView_QueryItemText(int row, int column, out string text) { - if (column == 1) - text = log.Names[row]; - else - text = row.ToString(); + text = column == 1 + ? Log.Names[row] + : row.ToString(); } + private void HistoryView_QueryItemBkColor(int row, int column, ref Color color) { if (column == 0) + { return; + } - if (row == log.UndoIndex) + if (row == Log.UndoIndex) + { color = TAStudio.GreenZone_InputLog; - else if (row > log.UndoIndex) + } + else if (row > Log.UndoIndex) + { color = TAStudio.LagZone_InputLog; + } } - private string _lastUndoAction = null; public void UpdateValues() { - HistoryView.ItemCount = log.Names.Count; - if (AutoScrollCheck.Checked && _lastUndoAction != log.NextUndoStepName) + HistoryView.ItemCount = Log.Names.Count; + if (AutoScrollCheck.Checked && _lastUndoAction != Log.NextUndoStepName) { - HistoryView.ensureVisible(log.UndoIndex); + HistoryView.ensureVisible(Log.UndoIndex); HistoryView.clearSelection(); - HistoryView.SelectItem(log.UndoIndex - 1, true); + HistoryView.SelectItem(Log.UndoIndex - 1, true); } - _lastUndoAction = log.NextUndoStepName; + + _lastUndoAction = Log.NextUndoStepName; HistoryView.Refresh(); } private void ClearButton_Click(object sender, EventArgs e) { - log.ClearLog(); + Log.ClearLog(); UpdateValues(); } + private void UndoButton_Click(object sender, EventArgs e) { - log.Undo(); - tastudio.RefreshDialog(); - } - private void RedoButton_Click(object sender, EventArgs e) - { - log.Redo(); - tastudio.RefreshDialog(); + Log.Undo(); + _tastudio.RefreshDialog(); } + private void RedoButton_Click(object sender, EventArgs e) + { + Log.Redo(); + _tastudio.RefreshDialog(); + } private void HistoryView_DoubleClick(object sender, EventArgs e) { - if (log.UndoIndex <= HistoryView.selectedItem) + if (Log.UndoIndex <= HistoryView.selectedItem) + { return; + } do { - log.Undo(); - } while (log.UndoIndex > HistoryView.selectedItem); + Log.Undo(); + } + while (Log.UndoIndex > HistoryView.selectedItem); + UpdateValues(); } + private void HistoryView_MouseUp(object sender, MouseEventArgs e) { - if (e.Button == System.Windows.Forms.MouseButtons.Right) + if (e.Button == MouseButtons.Right) + { RightClickMenu.Show(HistoryView, e.X, e.Y); - else if (e.Button == System.Windows.Forms.MouseButtons.Left) + } + else if (e.Button == MouseButtons.Left) { if (HistoryView.selectedItem == -1) + { HistoryView.SelectItem(_hackSelect, true); + } } } + // Hacky way to select a row by clicking the names row - int _hackSelect = -1; + private int _hackSelect = -1; + private void HistoryView_MouseDown(object sender, MouseEventArgs e) { - HistoryView.SelectItem(e.Y / HistoryView.LineHeight + HistoryView.VScrollPos - 1, true); + HistoryView.SelectItem((e.Y / HistoryView.LineHeight) + HistoryView.VScrollPos - 1, true); _hackSelect = HistoryView.selectedItem; } - private void undoHereToolStripMenuItem_Click(object sender, EventArgs e) + private void UndoHereMenuItem_Click(object sender, EventArgs e) { - if (HistoryView.selectedItem == -1 || log.UndoIndex < HistoryView.selectedItem) + if (HistoryView.selectedItem == -1 || Log.UndoIndex < HistoryView.selectedItem) + { return; + } do { - log.Undo(); - } while (log.UndoIndex >= HistoryView.selectedItem); + Log.Undo(); + } + while (Log.UndoIndex >= HistoryView.selectedItem); + UpdateValues(); } - private void redoHereToolStripMenuItem_Click(object sender, EventArgs e) + + private void RedoHereMenuItem_Click(object sender, EventArgs e) { - if (HistoryView.selectedItem == -1 || log.UndoIndex >= HistoryView.selectedItem) + if (HistoryView.selectedItem == -1 || Log.UndoIndex >= HistoryView.selectedItem) + { return; + } do { - log.Redo(); - } while (log.UndoIndex < HistoryView.selectedItem); + Log.Redo(); + } + while (Log.UndoIndex < HistoryView.selectedItem); + UpdateValues(); } - private void clearHistoryToHereToolStripMenuItem_Click(object sender, EventArgs e) + + private void ClearHistoryToHereMenuItem_Click(object sender, EventArgs e) { if (HistoryView.selectedItem != -1) - log.ClearLog(HistoryView.selectedItem); + { + Log.ClearLog(HistoryView.selectedItem); + } + UpdateValues(); } private void MaxStepsNum_ValueChanged(object sender, EventArgs e) { - log.MaxSteps = (int)MaxStepsNum.Value; + Log.MaxSteps = (int)MaxStepsNum.Value; } - - - } } diff --git a/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs b/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs index c8bc53a532..2d66b548cd 100644 --- a/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs +++ b/BizHawk.Client.EmuHawk/tools/TI83/TI83KeyPad.cs @@ -1,6 +1,5 @@ using System; -using System.Collections.Generic; -using System.Windows.Forms; + using BizHawk.Client.Common; using BizHawk.Emulation.Cores.Calculators; using BizHawk.Emulation.Common; @@ -39,9 +38,9 @@ namespace BizHawk.Client.EmuHawk #region Public API public bool AskSaveChanges() { return true; } - public bool UpdateBefore { get { return false; } } + public bool UpdateBefore => false; - public void NewUpdate(ToolFormUpdateType type) { } + public void NewUpdate(ToolFormUpdateType type) { } public void UpdateValues() { diff --git a/BizHawk.Client.EmuHawk/tools/ToolManager.cs b/BizHawk.Client.EmuHawk/tools/ToolManager.cs index c45a1dd6b0..243a412927 100644 --- a/BizHawk.Client.EmuHawk/tools/ToolManager.cs +++ b/BizHawk.Client.EmuHawk/tools/ToolManager.cs @@ -5,20 +5,16 @@ using System.IO; using System.Linq; using System.Reflection; using System.ComponentModel; +using System.Windows.Forms; -using BizHawk.Emulation.Common.IEmulatorExtensions; using BizHawk.Client.Common; using BizHawk.Emulation.Common; using BizHawk.Common.ReflectionExtensions; -using System.Windows.Forms; - namespace BizHawk.Client.EmuHawk { public class ToolManager { - #region Fields - private readonly Form _owner; // TODO: merge ToolHelper code where logical @@ -26,12 +22,8 @@ namespace BizHawk.Client.EmuHawk // Also a UsesRam, and similar method private readonly List _tools = new List(); - #endregion - - #region cTor(s) - /// - /// Initialize an new ToolManager instance + /// Initializes a new instance of the class. /// /// Form that handle the ToolManager public ToolManager(Form owner) @@ -39,28 +31,24 @@ namespace BizHawk.Client.EmuHawk _owner = owner; } - #endregion - /// - /// Loads the tool dialog T (T must implemants ) , if it does not exist it will be created, if it is already open, it will be focused + /// Loads the tool dialog T (T must implements ) , if it does not exist it will be created, if it is already open, it will be focused /// This method should be used only if you can't use the generic one /// /// Type of tool you want to load /// Define if the tool form has to get the focus or not (Default is true) - /// An instanciated + /// An instantiated /// Raised if can't be casted into IToolForm internal IToolForm Load(Type toolType, bool focus = true) { if (!typeof(IToolForm).IsAssignableFrom(toolType)) { - throw new ArgumentException(string.Format("Type {0} does not implement IToolForm.", toolType.Name)); - } - else - { - //The type[] in parameter is used to avoid an ambigous name exception - MethodInfo method = GetType().GetMethod("Load", new Type[] { typeof(bool) }).MakeGenericMethod(toolType); - return (IToolForm)method.Invoke(this, new object[] { focus }); + throw new ArgumentException($"Type {toolType.Name} does not implement IToolForm."); } + + // The type[] in parameter is used to avoid an ambigous name exception + MethodInfo method = GetType().GetMethod("Load", new Type[] { typeof(bool) }).MakeGenericMethod(toolType); + return (IToolForm)method.Invoke(this, new object[] { focus }); } /// @@ -68,7 +56,7 @@ namespace BizHawk.Client.EmuHawk /// /// Type of tool you want to load /// Define if the tool form has to get the focus or not (Default is true) - /// An instanciated + /// An instantiated public T Load(bool focus = true) where T : class, IToolForm { @@ -79,9 +67,9 @@ namespace BizHawk.Client.EmuHawk /// Loads the tool dialog T (T must implement ) , if it does not exist it will be created, if it is already open, it will be focused /// /// Type of tool you want to load + /// Path to the .dll of the external tool /// Define if the tool form has to get the focus or not (Default is true) - /// Path to the dll of the external tool - /// An instanciated + /// An instantiated public T Load(string toolPath, bool focus = true) where T : class, IToolForm { @@ -95,11 +83,11 @@ namespace BizHawk.Client.EmuHawk T existingTool; if (isExternal) { - existingTool = (T)_tools.FirstOrDefault(x => x is T && x.GetType().Assembly.Location == toolPath); + existingTool = (T)_tools.FirstOrDefault(t => t is T && t.GetType().Assembly.Location == toolPath); } else { - existingTool = (T)_tools.FirstOrDefault(x => x is T); + existingTool = (T)_tools.FirstOrDefault(t => t is T); } if (existingTool != null) @@ -144,6 +132,7 @@ namespace BizHawk.Client.EmuHawk settings = new ToolDialogSettings(); Global.Config.CommonToolSettings[toolType] = settings; } + AttachSettingHooks(newTool as IToolFormAutoConfig, settings); } @@ -156,6 +145,7 @@ namespace BizHawk.Client.EmuHawk settings = new Dictionary(); Global.Config.CustomToolSettings[toolType] = settings; } + InstallCustomConfig(newTool, settings); } @@ -171,7 +161,7 @@ namespace BizHawk.Client.EmuHawk .Select(kvp => kvp.Key); var customSettings = Global.Config.CustomToolSettings - .Where(list => list.Value.Any(kvp => typeof(ToolDialogSettings).IsAssignableFrom(kvp.Value.GetType()) && (kvp.Value as ToolDialogSettings).AutoLoad)) + .Where(list => list.Value.Any(kvp => kvp.Value is ToolDialogSettings && ((ToolDialogSettings)kvp.Value).AutoLoad)) .Select(kvp => kvp.Key); var typeNames = genericSettings.Concat(customSettings); @@ -193,10 +183,10 @@ namespace BizHawk.Client.EmuHawk private static void RefreshSettings(Form form, ToolStripItemCollection menu, ToolDialogSettings settings, int idx) { - (menu[idx + 0] as ToolStripMenuItem).Checked = settings.SaveWindowPosition; - (menu[idx + 1] as ToolStripMenuItem).Checked = settings.TopMost; - (menu[idx + 2] as ToolStripMenuItem).Checked = settings.FloatingWindow; - (menu[idx + 3] as ToolStripMenuItem).Checked = settings.AutoLoad; + ((ToolStripMenuItem)menu[idx + 0]).Checked = settings.SaveWindowPosition; + ((ToolStripMenuItem)menu[idx + 1]).Checked = settings.TopMost; + ((ToolStripMenuItem)menu[idx + 2]).Checked = settings.FloatingWindow; + ((ToolStripMenuItem)menu[idx + 3]).Checked = settings.AutoLoad; form.TopMost = settings.TopMost; @@ -223,17 +213,22 @@ namespace BizHawk.Client.EmuHawk break; } } + if (dest == null) { var submenu = new ToolStripMenuItem("&Settings"); ms.Items.Add(submenu); dest = submenu.DropDownItems; } + break; } } + if (dest == null) + { throw new InvalidOperationException("IToolFormAutoConfig must have menu to bind to!"); + } int idx = dest.Count; @@ -250,10 +245,13 @@ namespace BizHawk.Client.EmuHawk form.StartPosition = FormStartPosition.Manual; form.Location = settings.WindowPosition; } + if (settings.UseWindowSize) { if (form.FormBorderStyle == FormBorderStyle.Sizable || form.FormBorderStyle == FormBorderStyle.SizableToolWindow) + { form.Size = settings.WindowSize; + } } form.FormClosing += (o, e) => @@ -262,8 +260,16 @@ namespace BizHawk.Client.EmuHawk { settings.Wndx = form.Location.X; settings.Wndy = form.Location.Y; - if (settings.Wndx < 0) settings.Wndx = 0; - if (settings.Wndy < 0) settings.Wndy = 0; + if (settings.Wndx < 0) + { + settings.Wndx = 0; + } + + if (settings.Wndy < 0) + { + settings.Wndy = 0; + } + settings.Width = form.Right - form.Left; // why not form.Size.Width? settings.Height = form.Bottom - form.Top; } @@ -271,29 +277,29 @@ namespace BizHawk.Client.EmuHawk dest[idx + 0].Click += (o, e) => { - bool val = !(o as ToolStripMenuItem).Checked; + bool val = !((ToolStripMenuItem)o).Checked; settings.SaveWindowPosition = val; - (o as ToolStripMenuItem).Checked = val; + ((ToolStripMenuItem)o).Checked = val; }; dest[idx + 1].Click += (o, e) => { - bool val = !(o as ToolStripMenuItem).Checked; + bool val = !((ToolStripMenuItem)o).Checked; settings.TopMost = val; - (o as ToolStripMenuItem).Checked = val; + ((ToolStripMenuItem)o).Checked = val; form.TopMost = val; }; dest[idx + 2].Click += (o, e) => { - bool val = !(o as ToolStripMenuItem).Checked; + bool val = !((ToolStripMenuItem)o).Checked; settings.FloatingWindow = val; - (o as ToolStripMenuItem).Checked = val; + ((ToolStripMenuItem)o).Checked = val; form.Owner = val ? null : _owner; }; dest[idx + 3].Click += (o, e) => { - bool val = !(o as ToolStripMenuItem).Checked; + bool val = !((ToolStripMenuItem)o).Checked; settings.AutoLoad = val; - (o as ToolStripMenuItem).Checked = val; + ((ToolStripMenuItem)o).Checked = val; }; dest[idx + 4].Click += (o, e) => { @@ -313,7 +319,9 @@ namespace BizHawk.Client.EmuHawk Type type = tool.GetType(); var props = type.GetPropertiesWithAttrib(typeof(ConfigPersistAttribute)).ToList(); if (props.Count == 0) + { return; + } foreach (var prop in props) { @@ -329,18 +337,19 @@ namespace BizHawk.Client.EmuHawk // back on regular object serialization when needed. so try to undo a TypeConverter // operation here var converter = TypeDescriptor.GetConverter(prop.PropertyType); - val = converter.ConvertFromString(null,System.Globalization.CultureInfo.InvariantCulture,((string)val)); + val = converter.ConvertFromString(null, System.Globalization.CultureInfo.InvariantCulture, (string)val); } else if (!(val is bool) && prop.PropertyType.IsPrimitive) { // numeric constanst are similarly hosed val = Convert.ChangeType(val, prop.PropertyType, System.Globalization.CultureInfo.InvariantCulture); } + prop.SetValue(tool, val, null); } } - (tool as Form).FormClosing += (o, e) => SaveCustomConfig(tool, data, props); + ((Form)tool).FormClosing += (o, e) => SaveCustomConfig(tool, data, props); } private static void SaveCustomConfig(IToolForm tool, Dictionary data, List props) @@ -352,13 +361,13 @@ namespace BizHawk.Client.EmuHawk } } - /// /// Determines whether a given IToolForm is already loaded /// + /// Type of tool to check public bool IsLoaded() where T : IToolForm { - var existingTool = _tools.FirstOrDefault(x => x is T); + var existingTool = _tools.FirstOrDefault(t => t is T); if (existingTool != null) { return !existingTool.IsDisposed; @@ -376,14 +385,16 @@ namespace BizHawk.Client.EmuHawk /// /// Returns true if an instance of T exists /// + /// Type of tool to check public bool Has() where T : IToolForm { - return _tools.Any(x => x is T && !x.IsDisposed); + return _tools.Any(t => t is T && !t.IsDisposed); } /// /// Gets the instance of T, or creates and returns a new instance /// + /// Type of tool to get public IToolForm Get() where T : class, IToolForm { return Load(false); @@ -393,53 +404,58 @@ namespace BizHawk.Client.EmuHawk { get { - //return _tools.Where(t => !t.IsDisposed); return Assembly .GetAssembly(typeof(IToolForm)) .GetTypes() .Where(t => typeof(IToolForm).IsAssignableFrom(t)) .Where(t => !t.IsInterface) - .Where(t => IsAvailable(t)); + .Where(IsAvailable); } } public void UpdateBefore() { - var beforeList = _tools.Where(x => x.UpdateBefore); + var beforeList = _tools.Where(t => t.UpdateBefore); foreach (var tool in beforeList) { - if (!tool.IsDisposed || - (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed + if (!tool.IsDisposed + || (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed { tool.UpdateValues(); } } + foreach (var tool in _tools) + { tool.NewUpdate(ToolFormUpdateType.PreFrame); + } } public void UpdateAfter() { - var afterList = _tools.Where(x => !x.UpdateBefore); + var afterList = _tools.Where(t => !t.UpdateBefore); foreach (var tool in afterList) { - if (!tool.IsDisposed || - (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed + if (!tool.IsDisposed + || (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed { tool.UpdateValues(); } } foreach (var tool in _tools) + { tool.NewUpdate(ToolFormUpdateType.PostFrame); + } } /// /// Calls UpdateValues() on an instance of T, if it exists /// + /// Type of tool to update public void UpdateValues() where T : IToolForm { - var tool = _tools.FirstOrDefault(x => x is T); + var tool = _tools.FirstOrDefault(t => t is T); if (tool != null) { if (!tool.IsDisposed || @@ -488,13 +504,11 @@ namespace BizHawk.Client.EmuHawk /// /// Calls Restart() on an instance of T, if it exists /// + /// Type of tool to restart public void Restart() where T : IToolForm { - var tool = _tools.FirstOrDefault(x => x is T); - if (tool != null) - { - tool.Restart(); - } + var tool = _tools.FirstOrDefault(t => t is T); + tool?.Restart(); } /// @@ -516,6 +530,7 @@ namespace BizHawk.Client.EmuHawk /// Calls AskSave() on an instance of T, if it exists, else returns true /// The caller should interpret false as cancel and will back out of the action that invokes this call /// + /// Type of tool public bool AskSave() where T : IToolForm { if (Global.Config.SupressAskSave) // User has elected to not be nagged @@ -523,23 +538,22 @@ namespace BizHawk.Client.EmuHawk return true; } - var tool = _tools.FirstOrDefault(x => x is T); + var tool = _tools.FirstOrDefault(t => t is T); if (tool != null) { return tool.AskSaveChanges(); } - else - { - return false; - } + + return false; } /// /// If T exists, this call will close the tool, and remove it from memory /// + /// Type of tool to close public void Close() where T : IToolForm { - var tool = _tools.FirstOrDefault(x => x is T); + var tool = _tools.FirstOrDefault(t => t is T); if (tool != null) { tool.Close(); @@ -549,7 +563,7 @@ namespace BizHawk.Client.EmuHawk public void Close(Type toolType) { - var tool = _tools.FirstOrDefault(x => toolType.IsAssignableFrom(x.GetType())); + var tool = _tools.FirstOrDefault(toolType.IsInstanceOfType); if (tool != null) { @@ -560,7 +574,7 @@ namespace BizHawk.Client.EmuHawk public void Close() { - _tools.ForEach(x => x.Close()); + _tools.ForEach(t => t.Close()); _tools.Clear(); } @@ -568,7 +582,7 @@ namespace BizHawk.Client.EmuHawk /// Create a new instance of an IToolForm and return it /// /// Type of tool you want to create - /// Path dll for an external tool + /// Path .dll for an external tool /// New instance of an IToolForm private IToolForm CreateInstance(string dllPath) where T : IToolForm @@ -586,13 +600,14 @@ namespace BizHawk.Client.EmuHawk { IToolForm tool; - //Specific case for custom tools - //TODO: Use AppDomain in order to be able to unload the assembly - //Hard stuff as we need a proxy object that inherit from MarshalByRefObject. + // Specific case for custom tools + // TODO: Use AppDomain in order to be able to unload the assembly + // Hard stuff as we need a proxy object that inherit from MarshalByRefObject. if (toolType == typeof(IExternalToolForm)) { - if (MessageBox.Show("Are you sure want to load this external tool?\r\nAccept ONLY if you trust the source and if you know what you're doing. In any other case, choose no." - , "Confirmm loading", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + if (MessageBox.Show( + "Are you sure want to load this external tool?\r\nAccept ONLY if you trust the source and if you know what you're doing. In any other case, choose no.", + "Confirmm loading", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { try { @@ -635,7 +650,7 @@ namespace BizHawk.Client.EmuHawk { if (!fromLua) { - LuaConsole.StartLuaDrawing(); + LuaConsole.LuaImp.StartLuaDrawing(); } } @@ -655,18 +670,18 @@ namespace BizHawk.Client.EmuHawk { if (!fromLua) { - LuaConsole.EndLuaDrawing(); + LuaConsole.LuaImp.EndLuaDrawing(); } } } public void FastUpdateBefore() { - var beforeList = _tools.Where(x => x.UpdateBefore); + var beforeList = _tools.Where(t => t.UpdateBefore); foreach (var tool in beforeList) { - if (!tool.IsDisposed || - (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed + if (!tool.IsDisposed + || (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed { tool.FastUpdate(); } @@ -680,11 +695,11 @@ namespace BizHawk.Client.EmuHawk LuaConsole.ResumeScripts(true); } - var afterList = _tools.Where(x => !x.UpdateBefore); + var afterList = _tools.Where(t => !t.UpdateBefore); foreach (var tool in afterList) { - if (!tool.IsDisposed || - (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed + if (!tool.IsDisposed + || (tool is RamWatch && Global.Config.DisplayRamWatch)) // RAM Watch hack, on screen display should run even if RAM Watch is closed { tool.FastUpdate(); } @@ -692,7 +707,7 @@ namespace BizHawk.Client.EmuHawk if (Global.Config.RunLuaDuringTurbo && Has()) { - LuaConsole.EndLuaDrawing(); + LuaConsole.LuaImp.EndLuaDrawing(); } } @@ -722,13 +737,8 @@ namespace BizHawk.Client.EmuHawk .OfType() .FirstOrDefault(); - if (attr == null) // If no attributes there is no supported systems documented so assume all - { - return true; - } - // If no supported systems mentioned assume all - if (attr.SupportedSystems != null && attr.SupportedSystems.Any()) + if (attr?.SupportedSystems != null && attr.SupportedSystems.Any()) { return attr.SupportedSystems.Contains(Global.Emulator.SystemId); } @@ -743,7 +753,7 @@ namespace BizHawk.Client.EmuHawk { get { - var tool = _tools.FirstOrDefault(x => x is RamWatch); + var tool = _tools.FirstOrDefault(t => t is RamWatch); if (tool != null) { if (tool.IsDisposed) @@ -766,7 +776,7 @@ namespace BizHawk.Client.EmuHawk { get { - var tool = _tools.FirstOrDefault(x => x is RamSearch); + var tool = _tools.FirstOrDefault(t => t is RamSearch); if (tool != null) { if (tool.IsDisposed) @@ -789,7 +799,7 @@ namespace BizHawk.Client.EmuHawk { get { - var tool = _tools.FirstOrDefault(x => x is Cheats); + var tool = _tools.FirstOrDefault(t => t is Cheats); if (tool != null) { if (tool.IsDisposed) @@ -812,7 +822,7 @@ namespace BizHawk.Client.EmuHawk { get { - var tool = _tools.FirstOrDefault(x => x is HexEditor); + var tool = _tools.FirstOrDefault(t => t is HexEditor); if (tool != null) { if (tool.IsDisposed) @@ -835,7 +845,7 @@ namespace BizHawk.Client.EmuHawk { get { - var tool = _tools.FirstOrDefault(x => x is VirtualpadTool); + var tool = _tools.FirstOrDefault(t => t is VirtualpadTool); if (tool != null) { if (tool.IsDisposed) @@ -858,7 +868,7 @@ namespace BizHawk.Client.EmuHawk { get { - var tool = _tools.FirstOrDefault(x => x is SNESGraphicsDebugger); + var tool = _tools.FirstOrDefault(t => t is SNESGraphicsDebugger); if (tool != null) { if (tool.IsDisposed) @@ -881,7 +891,7 @@ namespace BizHawk.Client.EmuHawk { get { - var tool = _tools.FirstOrDefault(x => x is LuaConsole); + var tool = _tools.FirstOrDefault(t => t is LuaConsole); if (tool != null) { if (tool.IsDisposed) @@ -906,9 +916,11 @@ namespace BizHawk.Client.EmuHawk { // prevent nasty silent corruption if (!GlobalWin.Tools.IsLoaded()) + { System.Diagnostics.Debug.Fail("TAStudio does not exist!"); + } - var tool = _tools.FirstOrDefault(x => x is TAStudio); + var tool = _tools.FirstOrDefault(t => t is TAStudio); if (tool != null) { if (tool.IsDisposed) diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/IVirtualPadControl.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/IVirtualPadControl.cs index 23678e9c72..6045c8f13f 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/IVirtualPadControl.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/IVirtualPadControl.cs @@ -18,7 +18,7 @@ namespace BizHawk.Client.EmuHawk void Set(IController controller); /// - /// Gets or sets whether or not the user can change the state of the control + /// Gets or sets a value indicating whether or not the user can change the state of the control /// bool ReadOnly { get; set; } } diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogButton.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogButton.cs index f4bbb50ebd..ddc2b76b4e 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogButton.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/controls/VirtualPadAnalogButton.cs @@ -179,15 +179,29 @@ namespace BizHawk.Client.EmuHawk private void UpdateTickFrequency() { - if (AnalogTrackBar == null) return; - //try to base it on the width, lets make a tick every 10 pixels at the minimum + if (AnalogTrackBar == null) + { + return; + } + + // try to base it on the width, lets make a tick every 10 pixels at the minimum int canDoTicks = AnalogTrackBar.Width / 10; - if (canDoTicks < 2) canDoTicks = 2; + if (canDoTicks < 2) + { + canDoTicks = 2; + } + int range = _maxValue - _minValue + 1; if (range < canDoTicks) + { canDoTicks = range; + } + if (canDoTicks <= 0) + { canDoTicks = 1; + } + AnalogTrackBar.TickFrequency = range / canDoTicks; } @@ -242,6 +256,7 @@ namespace BizHawk.Client.EmuHawk _programmaticallyChangingValue = false; } } + protected override void OnPaint(PaintEventArgs e) { RefreshWidgets(); diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/A78Schema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/A78Schema.cs index 6e9809b3e4..a1f51ede4f 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/A78Schema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/A78Schema.cs @@ -11,7 +11,7 @@ namespace BizHawk.Client.EmuHawk { public IEnumerable GetPadSchemas(IEmulator core) { - switch ((core as Atari7800).ControlAdapter.ControlType.Name) + switch (((Atari7800)core).ControlAdapter.ControlType.Name) { case "Atari 7800 Joystick Controller": yield return JoystickController(1); @@ -37,7 +37,6 @@ namespace BizHawk.Client.EmuHawk break; } - yield return ConsoleButtons(); } @@ -197,7 +196,7 @@ namespace BizHawk.Client.EmuHawk Location = new Point(14, 17), Type = PadSchema.PadInputType.TargetedPair, TargetSize = new Size(256, 240), - SecondaryNames = new [] + SecondaryNames = new[] { "P" + controller + " HPos", } diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/AppleIISchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/AppleIISchema.cs index a0298b78e8..fff1dbfddd 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/AppleIISchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/AppleIISchema.cs @@ -402,7 +402,6 @@ namespace BizHawk.Client.EmuHawk Location = new Point(315, 90), Type = PadSchema.PadInputType.Boolean }, - /************************** Row 5 **************************/ @@ -427,7 +426,6 @@ namespace BizHawk.Client.EmuHawk Location = new Point(96, 114), Type = PadSchema.PadInputType.Boolean }, - new PadSchema.ButtonSchema { diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/ColecoSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/ColecoSchema.cs index d357201015..1ad314d76d 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/ColecoSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/ColecoSchema.cs @@ -20,7 +20,8 @@ namespace BizHawk.Client.EmuHawk { break; } - else if (ports[i] == typeof(StandardController)) + + if (ports[i] == typeof(StandardController)) { yield return StandardController(i + 1); } @@ -181,7 +182,7 @@ namespace BizHawk.Client.EmuHawk }; } - public static PadSchema TurboController(int controller) + private static PadSchema TurboController(int controller) { return new PadSchema { @@ -213,7 +214,7 @@ namespace BizHawk.Client.EmuHawk }; } - public static PadSchema SuperActionController(int controller) + private static PadSchema SuperActionController(int controller) { return new PadSchema { diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/DualGBSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/DualGBSchema.cs index f24ebafa09..d7acfc41e1 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/DualGBSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/DualGBSchema.cs @@ -3,7 +3,7 @@ using System.Drawing; using BizHawk.Emulation.Common; -namespace BizHawk.Client.EmuHawk.tools.VirtualPads.schema +namespace BizHawk.Client.EmuHawk { [SchemaAttributes("DGB")] public class DualGBSchema : IVirtualPadSchema @@ -86,5 +86,4 @@ namespace BizHawk.Client.EmuHawk.tools.VirtualPads.schema }; } } - } diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/GBSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/GBSchema.cs index 80c69212a8..2044d5a493 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/GBSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/GBSchema.cs @@ -14,7 +14,7 @@ namespace BizHawk.Client.EmuHawk yield return ConsoleButtons(); } - public static PadSchema StandardController() + private static PadSchema StandardController() { return new PadSchema { diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/GenSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/GenSchema.cs index e37e294f13..8805d794e0 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/GenSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/GenSchema.cs @@ -48,7 +48,7 @@ namespace BizHawk.Client.EmuHawk yield return ConsoleButtons(); } - public static PadSchema ThreeButtonController(int controller) + private static PadSchema ThreeButtonController(int controller) { return new PadSchema { @@ -120,7 +120,7 @@ namespace BizHawk.Client.EmuHawk }; } - public static PadSchema SixButtonController(int controller) + private static PadSchema SixButtonController(int controller) { return new PadSchema { @@ -213,7 +213,7 @@ namespace BizHawk.Client.EmuHawk }; } - public static PadSchema LightGun(int controller) + private static PadSchema LightGun(int controller) { return new PadSchema { @@ -229,7 +229,7 @@ namespace BizHawk.Client.EmuHawk Type = PadSchema.PadInputType.TargetedPair, MaxValue = 10000, TargetSize = new Size(320, 240), - SecondaryNames = new [] + SecondaryNames = new[] { "P" + controller + " Lightgun Y", } @@ -252,7 +252,7 @@ namespace BizHawk.Client.EmuHawk }; } - public static PadSchema Mouse(int controller) + private static PadSchema Mouse(int controller) { return new PadSchema { @@ -268,7 +268,7 @@ namespace BizHawk.Client.EmuHawk Type = PadSchema.PadInputType.AnalogStick, MaxValue = 255, TargetSize = new Size(520, 570), - SecondaryNames = new [] + SecondaryNames = new[] { "P" + controller + " Mouse Y", } @@ -305,7 +305,7 @@ namespace BizHawk.Client.EmuHawk }; } - public static PadSchema ConsoleButtons() + private static PadSchema ConsoleButtons() { return new PadSchema { @@ -332,7 +332,7 @@ namespace BizHawk.Client.EmuHawk }; } - public static PadSchema Activator(int controller) + private static PadSchema Activator(int controller) { return new PadSchema { @@ -411,7 +411,7 @@ namespace BizHawk.Client.EmuHawk }; } - public static PadSchema XE1AP(int controller) + private static PadSchema XE1AP(int controller) { return new PadSchema { diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/IntvSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/IntvSchema.cs index 0a73b7e850..1b5f42b4e0 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/IntvSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/IntvSchema.cs @@ -10,9 +10,9 @@ namespace BizHawk.Client.EmuHawk [SchemaAttributes("INTV")] public class IntvSchema : IVirtualPadSchema { - private string UnpluggedControllerName { get { return typeof(UnpluggedController).DisplayName(); } } - private string StandardControllerName { get { return typeof(StandardController).DisplayName(); } } - private string AnalogControllerName { get { return typeof(FakeAnalogController).DisplayName(); } } + private string UnpluggedControllerName => typeof(UnpluggedController).DisplayName(); + private string StandardControllerName => typeof(StandardController).DisplayName(); + private string AnalogControllerName => typeof(FakeAnalogController).DisplayName(); public IEnumerable GetPadSchemas(IEmulator core) { diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/LynxSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/LynxSchema.cs index 41efec4445..72859eaa2e 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/LynxSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/LynxSchema.cs @@ -6,7 +6,7 @@ using BizHawk.Emulation.Common; namespace BizHawk.Client.EmuHawk { [SchemaAttributes("Lynx")] - public class LYNXSchema : IVirtualPadSchema + public class LynxSchema : IVirtualPadSchema { public IEnumerable GetPadSchemas(IEmulator core) { @@ -14,7 +14,7 @@ namespace BizHawk.Client.EmuHawk //yield return ConsoleButtons(); } - public static PadSchema StandardController() + private static PadSchema StandardController() { return new PadSchema { diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/N64Schema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/N64Schema.cs index 3bef308cd9..925849abcf 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/N64Schema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/N64Schema.cs @@ -21,7 +21,7 @@ namespace BizHawk.Client.EmuHawk } } - public static PadSchema StandardController(int controller) + private static PadSchema StandardController(int controller) { return new PadSchema { diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/NesSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/NesSchema.cs index 1dd85dd3d1..83b95d1bdc 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/NesSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/NesSchema.cs @@ -16,7 +16,7 @@ namespace BizHawk.Client.EmuHawk { if (core is NES) { - var nes = core as NES; + var nes = (NES)core; var ss = nes.GetSyncSettings(); var isFds = nes.IsFDS; @@ -46,7 +46,6 @@ namespace BizHawk.Client.EmuHawk case "OekaKids": yield return OekaKidsTablet(3); break; - } } else @@ -129,7 +128,7 @@ namespace BizHawk.Client.EmuHawk var ss = ((QuickNES)core).GetSyncSettings(); if (ss.LeftPortConnected == true && ss.RightPortConnected == true) { - //Set both controllers + // Set both controllers yield return StandardController(1); yield return StandardController(2); } @@ -141,6 +140,7 @@ namespace BizHawk.Client.EmuHawk { yield return StandardController(1); } + yield return NesConsoleButtons(); } } @@ -383,7 +383,7 @@ namespace BizHawk.Client.EmuHawk Location = new Point(14, 17), Type = PadSchema.PadInputType.TargetedPair, TargetSize = new Size(256, 240), - SecondaryNames = new [] + SecondaryNames = new[] { "P" + controller + " Zapper Y", } @@ -543,7 +543,7 @@ namespace BizHawk.Client.EmuHawk Location = new Point(14, 17), Type = PadSchema.PadInputType.TargetedPair, TargetSize = new Size(256, 240), - SecondaryNames = new [] + SecondaryNames = new[] { "P" + controller + " Pen Y", } diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/PSXSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/PSXSchema.cs index aa8264fb2b..e307438784 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/PSXSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/PSXSchema.cs @@ -12,7 +12,7 @@ namespace BizHawk.Client.EmuHawk { public IEnumerable GetPadSchemas(IEmulator core) { - var psx = ((Octoshock)core); + var psx = (Octoshock)core; var settings = psx.GetSyncSettings(); var fioConfig = settings.FIOConfig.ToLogical(); @@ -43,7 +43,7 @@ namespace BizHawk.Client.EmuHawk yield return ConsoleButtons(psx); } - public static PadSchema DualShockController(int controller) + private static PadSchema DualShockController(int controller) { return new PadSchema { @@ -202,7 +202,7 @@ namespace BizHawk.Client.EmuHawk }; } - public static PadSchema GamePadController(int controller) + private static PadSchema GamePadController(int controller) { return new PadSchema { @@ -456,12 +456,12 @@ namespace BizHawk.Client.EmuHawk }, new PadSchema.ButtonSchema { - Name = "Disc Select", //not really, but shuts up a warning + Name = "Disc Select", // not really, but shuts up a warning Type = PadSchema.PadInputType.DiscManager, - Location = new Point(10,54), - TargetSize = new Size(300,300), + Location = new Point(10, 54), + TargetSize = new Size(300, 300), OwnerEmulator = psx, - SecondaryNames = new [] { "Open", "Close", "Disc Select" } + SecondaryNames = new[] { "Open", "Close", "Disc Select" } } } }; diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/PceSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/PceSchema.cs index 65505bfc0f..b0ed56f313 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/PceSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/PceSchema.cs @@ -19,7 +19,7 @@ namespace BizHawk.Client.EmuHawk } } - public static PadSchema StandardController(int controller) + private static PadSchema StandardController(int controller) { return new PadSchema { diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SatSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SatSchema.cs index e70c60e8da..6263d5bb53 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SatSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SatSchema.cs @@ -15,7 +15,7 @@ namespace BizHawk.Client.EmuHawk yield return ConsoleButtons(); } - public static PadSchema StandardController(int controller) + private static PadSchema StandardController(int controller) { return new PadSchema { diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SchemaAttributes.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SchemaAttributes.cs index 2d4ec6b72a..feb84f29fe 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SchemaAttributes.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SchemaAttributes.cs @@ -6,7 +6,7 @@ namespace BizHawk.Client.EmuHawk public class SchemaAttributes : Attribute { /// - /// The system id associated with this schema + /// Gets the system id associated with this schema /// public string SystemId { get; private set; } diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SmsSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SmsSchema.cs index a43ae506bf..50d3718077 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SmsSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SmsSchema.cs @@ -11,7 +11,7 @@ namespace BizHawk.Client.EmuHawk { public IEnumerable GetPadSchemas(IEmulator core) { - if ((core as SMS).IsGameGear) + if (((SMS)core).IsGameGear) { yield return GGController(1); yield return GGConsoleButtons(); @@ -24,7 +24,7 @@ namespace BizHawk.Client.EmuHawk } } - public static PadSchema StandardController(int controller) + private static PadSchema StandardController(int controller) { return new PadSchema { @@ -78,7 +78,7 @@ namespace BizHawk.Client.EmuHawk }; } - public static PadSchema GGController(int controller) + private static PadSchema GGController(int controller) { return new PadSchema { diff --git a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SnesSchema.cs b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SnesSchema.cs index 2e2694ea27..5f02e974e0 100644 --- a/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SnesSchema.cs +++ b/BizHawk.Client.EmuHawk/tools/VirtualPads/schema/SnesSchema.cs @@ -36,7 +36,6 @@ namespace BizHawk.Client.EmuHawk for (int j = 0; j < 4; j++) { yield return StandardController(playerNum + j); - } offset += 3; @@ -118,8 +117,7 @@ namespace BizHawk.Client.EmuHawk Location = new Point(174, 10), Type = PadSchema.PadInputType.Boolean }, - - + new PadSchema.ButtonSchema { Name = "P" + controller + " Select", @@ -222,7 +220,7 @@ namespace BizHawk.Client.EmuHawk Location = new Point(14, 17), Type = PadSchema.PadInputType.TargetedPair, TargetSize = new Size(256, 240), - SecondaryNames = new [] + SecondaryNames = new[] { "P" + controller + " Scope Y", } @@ -275,7 +273,7 @@ namespace BizHawk.Client.EmuHawk Location = new Point(14, 17), Type = PadSchema.PadInputType.TargetedPair, TargetSize = new Size(256, 240), - SecondaryNames = new [] + SecondaryNames = new[] { "P" + controller + " Justifier Y", } diff --git a/BizHawk.Client.MultiHawk/Mainform.cs b/BizHawk.Client.MultiHawk/Mainform.cs index 7ff20054db..3001f38423 100644 --- a/BizHawk.Client.MultiHawk/Mainform.cs +++ b/BizHawk.Client.MultiHawk/Mainform.cs @@ -86,7 +86,7 @@ namespace BizHawk.Client.MultiHawk //CoreFileProvider.SyncCoreCommInputSignals(); Global.ActiveController = new Controller(NullController.Instance.Definition); - Global.AutoFireController = Global.AutofireNullControls; + Global.AutoFireController = AutofireNullControls; Global.AutofireStickyXORAdapter.SetOnOffPatternFromConfig(); Closing += (o, e) => @@ -149,7 +149,7 @@ namespace BizHawk.Client.MultiHawk } public EmulatorWindowList EmulatorWindows = new EmulatorWindowList(); - + private AutofireController AutofireNullControls; private bool _exit; protected override void OnClosed(EventArgs e) @@ -199,7 +199,7 @@ namespace BizHawk.Client.MultiHawk } Global.ClientControls = controls; - Global.AutofireNullControls = new AutofireController(NullController.Instance.Definition, Emulator); + AutofireNullControls = new AutofireController(NullController.Instance.Definition, Emulator); } private void OpenRomMenuItem_Click(object sender, EventArgs e) diff --git a/BizHawk.Emulation.Cores/BizHawk.Emulation.Cores.csproj b/BizHawk.Emulation.Cores/BizHawk.Emulation.Cores.csproj index 236ff7cce9..9869005551 100644 --- a/BizHawk.Emulation.Cores/BizHawk.Emulation.Cores.csproj +++ b/BizHawk.Emulation.Cores/BizHawk.Emulation.Cores.csproj @@ -221,6 +221,7 @@ C64.cs + @@ -369,6 +370,35 @@ + + + A7800Hawk.cs + + + A7800Hawk.cs + + + A7800Hawk.cs + + + A7800Hawk.cs + + + A7800Hawk.cs + + + A7800Hawk.cs + + + A7800Hawk.cs + + + + + + + + Atari7800.cs diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IInputPollable.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IInputPollable.cs index 7eff97d92d..90fa66b68e 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IInputPollable.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IInputPollable.cs @@ -2,7 +2,7 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64 { - public partial class C64// : IInputPollable + public partial class C64 : IInputPollable { public bool IsLagFrame { diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IMemoryDomains.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IMemoryDomains.cs index 6702481a28..f7265910f9 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IMemoryDomains.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/C64.IMemoryDomains.cs @@ -8,8 +8,11 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64 { private IMemoryDomains _memoryDomains; - private void SetupMemoryDomains(bool diskDriveEnabled) + private void SetupMemoryDomains() { + bool diskDriveEnabled = _board.DiskDrive != null; + bool tapeDriveEnabled = _board.TapeDrive != null; + var domains = new List { C64MemoryDomainFactory.Create("System Bus", 0x10000, a => _board.Cpu.Peek(a), (a, v) => _board.Cpu.Poke(a, v)), @@ -30,6 +33,15 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64 C64MemoryDomainFactory.Create("1541 VIA1", 0x10, a => _board.DiskDrive.PeekVia1(a), (a, v) => _board.DiskDrive.PokeVia1(a, v)) }); } + + if (tapeDriveEnabled) + { + domains.AddRange(new[] + { + C64MemoryDomainFactory.Create("Tape Data", _board.TapeDrive.TapeDataDomain.Length, a => _board.TapeDrive.TapeDataDomain[a], (a,v) => _board.TapeDrive.TapeDataDomain[a] = (byte)v) + }); + } + _memoryDomains = new MemoryDomainList(domains); ((BasicServiceProvider)ServiceProvider).Register(_memoryDomains); } diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/C64.Motherboard.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/C64.Motherboard.cs index ed8ea1b718..499a6ea006 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/C64.Motherboard.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/C64.Motherboard.cs @@ -169,7 +169,7 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64 public void Flush() { - Sid.Flush(); + Sid.Flush(true); } // ----------------------------------------- diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/C64.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/C64.cs index d33c794766..8b0b27046c 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/C64.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/C64.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; +using BizHawk.Common.BufferExtensions; using BizHawk.Emulation.Common; using BizHawk.Emulation.Cores.Computers.Commodore64.Cartridge; using BizHawk.Emulation.Cores.Computers.Commodore64.Media; @@ -15,7 +16,7 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64 isReleased: false)] public sealed partial class C64 : IEmulator, IRegionable, IBoardInfo { - public C64(CoreComm comm, IEnumerable roms, object settings, object syncSettings) + public C64(CoreComm comm, IEnumerable roms, GameInfo game, object settings, object syncSettings) { PutSyncSettings((C64SyncSettings)syncSettings ?? new C64SyncSettings()); @@ -31,9 +32,9 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64 RomSanityCheck(); Init(SyncSettings.VicType, Settings.BorderType, SyncSettings.SidType, SyncSettings.TapeDriveType, SyncSettings.DiskDriveType); - _cyclesPerFrame = _board.Vic.CyclesPerFrame; - SetupMemoryDomains(_board.DiskDrive != null); + _cyclesPerFrame = _board.Vic.CyclesPerFrame; _memoryCallbacks = new MemoryCallbackSystem(); + HardReset(); switch (SyncSettings.VicType) @@ -59,6 +60,14 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64 _tracer = new TraceBuffer { Header = _board.Cpu.TraceHeader }; ser.Register(_tracer); + + if (_board.CartPort.IsConnected) + { + // There are no multi-cart cart games, so just hardcode .First() + CoreComm.RomStatusDetails = $"{game.Name}\r\nSHA1:{roms.First().HashSHA1()}\r\nMD5:{roms.First().HashMD5()}\r\nMapper Impl \"{_board.CartPort.CartridgeType}\""; + } + + SetupMemoryDomains(); } // Currently we will require at least one rom. If multiple they MUST be all the same media type in the same format diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePortDevice.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePortDevice.cs index e05825db1e..4039e5c913 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePortDevice.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/CassettePortDevice.cs @@ -27,5 +27,8 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.Cassette } public abstract void SyncState(Serializer ser); + + // Exposed for memory domains, should not be used for actual emulation implementation + public abstract byte[] TapeDataDomain { get; } } } diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/TapeDrive.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/TapeDrive.cs index d0ebff1770..f94f00477e 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/TapeDrive.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/Cassette/TapeDrive.cs @@ -9,12 +9,18 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.Cassette public override void ExecutePhase2() { - if (_tape != null && !ReadMotor()) _tape.ExecuteCycle(); + if (_tape != null && !ReadMotor()) + { + _tape.ExecuteCycle(); + } } public override void HardReset() { - if (_tape != null) _tape.Rewind(); + if (_tape != null) + { + _tape.Rewind(); + } } public override bool ReadDataInputBuffer() @@ -41,5 +47,8 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.Cassette { _tape = null; } + + // Exposed for memory domains, should not be used for actual emulation implementation + public override byte[] TapeDataDomain => _tape.TapeDataDomain; } } diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/FFT.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/FFT.cs new file mode 100644 index 0000000000..1948acbf60 --- /dev/null +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/FFT.cs @@ -0,0 +1,667 @@ +using System; + +// Copyright(C) 1996-2001 Takuya Ooura +// C# port by J.D. Purcell +// You may use, copy, modify this code for any purpose and without fee. + +namespace BizHawk.Emulation.Cores.Computers.Commodore64 +{ + + public class RealFFT + { + private readonly int _length; + private readonly int[] _ip; + private readonly double[] _w; + + public readonly double ForwardScaleFactor; + public readonly double ReverseScaleFactor; + + public RealFFT(int length) + { + if (length < 2 || (length & (length - 1)) != 0) + { + throw new ArgumentException("length", "FFT length must be at least 2 and a power of 2."); + } + + _length = length; + _ip = new int[2 + (1 << (Convert.ToInt32(Math.Log(Math.Max(length / 4, 1), 2)) / 2))]; + _w = new double[length / 2]; + + ForwardScaleFactor = length; + ReverseScaleFactor = 0.5; + } + + public void ComputeForward(double[] buff) + { + Compute(buff, false); + } + + public void ComputeReverse(double[] buff) + { + Compute(buff, true); + } + + private void Compute(double[] buff, bool reverse) + { + if (buff.Length < _length) + { + throw new ArgumentException("buff", "Buffer length must be greater than or equal to the FFT length."); + } + + rdft(_length, reverse, buff, _ip, _w); + } + + private static void rdft(int n, bool rev, double[] a, int[] ip, double[] w) + { + int nw, nc; + double xi; + + nw = ip[0]; + if (n > (nw << 2)) + { + nw = n >> 2; + makewt(nw, ip, w); + } + nc = ip[1]; + if (n > (nc << 2)) + { + nc = n >> 2; + makect(nc, ip, w, nw); + } + if (!rev) + { + if (n > 4) + { + bitrv2(n, ip, a); + cftfsub(n, a, w); + rftfsub(n, a, nc, w, nw); + } + else if (n == 4) + { + cftfsub(n, a, w); + } + xi = a[0] - a[1]; + a[0] += a[1]; + a[1] = xi; + } + else + { + a[1] = 0.5 * (a[0] - a[1]); + a[0] -= a[1]; + if (n > 4) + { + rftbsub(n, a, nc, w, nw); + bitrv2(n, ip, a); + cftbsub(n, a, w); + } + else if (n == 4) + { + cftfsub(n, a, w); + } + } + } + + /* -------- initializing routines -------- */ + + private static void makewt(int nw, int[] ip, double[] w) + { + int j, nwh; + double delta, x, y; + + ip[0] = nw; + ip[1] = 1; + if (nw > 2) + { + nwh = nw >> 1; + delta = Math.Atan(1.0) / nwh; + w[0] = 1; + w[1] = 0; + w[nwh] = Math.Cos(delta * nwh); + w[nwh + 1] = w[nwh]; + if (nwh > 2) + { + for (j = 2; j < nwh; j += 2) + { + x = Math.Cos(delta * j); + y = Math.Sin(delta * j); + w[j] = x; + w[j + 1] = y; + w[nw - j] = y; + w[nw - j + 1] = x; + } + bitrv2(nw, ip, w); + } + } + } + + private static void makect(int nc, int[] ip, double[] c, int nw) + { + int j, nch; + double delta; + + ip[1] = nc; + if (nc > 1) + { + nch = nc >> 1; + delta = Math.Atan(1.0) / nch; + c[nw] = Math.Cos(delta * nch); + c[nw + nch] = 0.5 * c[nw]; + for (j = 1; j < nch; j++) + { + c[nw + j] = 0.5 * Math.Cos(delta * j); + c[nw + nc - j] = 0.5 * Math.Sin(delta * j); + } + } + } + + /* -------- child routines -------- */ + + private static void bitrv2(int n, int[] ip, double[] a) + { + int j, j1, k, k1, l, m, m2; + double xr, xi, yr, yi; + + ip[2] = 0; + l = n; + m = 1; + while ((m << 3) < l) + { + l >>= 1; + for (j = 0; j < m; j++) + { + ip[m + j + 2] = ip[j + 2] + l; + } + m <<= 1; + } + m2 = 2 * m; + if ((m << 3) == l) + { + for (k = 0; k < m; k++) + { + for (j = 0; j < k; j++) + { + j1 = 2 * j + ip[k + 2]; + k1 = 2 * k + ip[j + 2]; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 += 2 * m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 -= m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 += 2 * m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + } + j1 = 2 * k + m2 + ip[k + 2]; + k1 = j1 + m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + } + } + else + { + for (k = 1; k < m; k++) + { + for (j = 0; j < k; j++) + { + j1 = 2 * j + ip[k + 2]; + k1 = 2 * k + ip[j + 2]; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 += m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + } + } + } + } + + private static void cftfsub(int n, double[] a, double[] w) + { + int j, j1, j2, j3, l; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + l = 2; + if (n > 8) + { + cft1st(n, a, w); + l = 8; + while ((l << 2) < n) + { + cftmdl(n, l, a, w); + l <<= 2; + } + } + if ((l << 2) == n) + { + for (j = 0; j < l; j += 2) + { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + a[j2] = x0r - x2r; + a[j2 + 1] = x0i - x2i; + a[j1] = x1r - x3i; + a[j1 + 1] = x1i + x3r; + a[j3] = x1r + x3i; + a[j3 + 1] = x1i - x3r; + } + } + else + { + for (j = 0; j < l; j += 2) + { + j1 = j + l; + x0r = a[j] - a[j1]; + x0i = a[j + 1] - a[j1 + 1]; + a[j] += a[j1]; + a[j + 1] += a[j1 + 1]; + a[j1] = x0r; + a[j1 + 1] = x0i; + } + } + } + + private static void cftbsub(int n, double[] a, double[] w) + { + int j, j1, j2, j3, l; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + l = 2; + if (n > 8) + { + cft1st(n, a, w); + l = 8; + while ((l << 2) < n) + { + cftmdl(n, l, a, w); + l <<= 2; + } + } + if ((l << 2) == n) + { + for (j = 0; j < l; j += 2) + { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = -a[j + 1] - a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = -a[j + 1] + a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i - x2i; + a[j2] = x0r - x2r; + a[j2 + 1] = x0i + x2i; + a[j1] = x1r - x3i; + a[j1 + 1] = x1i - x3r; + a[j3] = x1r + x3i; + a[j3 + 1] = x1i + x3r; + } + } + else + { + for (j = 0; j < l; j += 2) + { + j1 = j + l; + x0r = a[j] - a[j1]; + x0i = -a[j + 1] + a[j1 + 1]; + a[j] += a[j1]; + a[j + 1] = -a[j + 1] - a[j1 + 1]; + a[j1] = x0r; + a[j1 + 1] = x0i; + } + } + } + + private static void cft1st(int n, double[] a, double[] w) + { + int j, k1, k2; + double wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + x0r = a[0] + a[2]; + x0i = a[1] + a[3]; + x1r = a[0] - a[2]; + x1i = a[1] - a[3]; + x2r = a[4] + a[6]; + x2i = a[5] + a[7]; + x3r = a[4] - a[6]; + x3i = a[5] - a[7]; + a[0] = x0r + x2r; + a[1] = x0i + x2i; + a[4] = x0r - x2r; + a[5] = x0i - x2i; + a[2] = x1r - x3i; + a[3] = x1i + x3r; + a[6] = x1r + x3i; + a[7] = x1i - x3r; + wk1r = w[2]; + x0r = a[8] + a[10]; + x0i = a[9] + a[11]; + x1r = a[8] - a[10]; + x1i = a[9] - a[11]; + x2r = a[12] + a[14]; + x2i = a[13] + a[15]; + x3r = a[12] - a[14]; + x3i = a[13] - a[15]; + a[8] = x0r + x2r; + a[9] = x0i + x2i; + a[12] = x2i - x0i; + a[13] = x0r - x2r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[10] = wk1r * (x0r - x0i); + a[11] = wk1r * (x0r + x0i); + x0r = x3i + x1r; + x0i = x3r - x1i; + a[14] = wk1r * (x0i - x0r); + a[15] = wk1r * (x0i + x0r); + k1 = 0; + for (j = 16; j < n; j += 16) + { + k1 += 2; + k2 = 2 * k1; + wk2r = w[k1]; + wk2i = w[k1 + 1]; + wk1r = w[k2]; + wk1i = w[k2 + 1]; + wk3r = wk1r - 2 * wk2i * wk1i; + wk3i = 2 * wk2i * wk1r - wk1i; + x0r = a[j] + a[j + 2]; + x0i = a[j + 1] + a[j + 3]; + x1r = a[j] - a[j + 2]; + x1i = a[j + 1] - a[j + 3]; + x2r = a[j + 4] + a[j + 6]; + x2i = a[j + 5] + a[j + 7]; + x3r = a[j + 4] - a[j + 6]; + x3i = a[j + 5] - a[j + 7]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j + 4] = wk2r * x0r - wk2i * x0i; + a[j + 5] = wk2r * x0i + wk2i * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j + 2] = wk1r * x0r - wk1i * x0i; + a[j + 3] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j + 6] = wk3r * x0r - wk3i * x0i; + a[j + 7] = wk3r * x0i + wk3i * x0r; + wk1r = w[k2 + 2]; + wk1i = w[k2 + 3]; + wk3r = wk1r - 2 * wk2r * wk1i; + wk3i = 2 * wk2r * wk1r - wk1i; + x0r = a[j + 8] + a[j + 10]; + x0i = a[j + 9] + a[j + 11]; + x1r = a[j + 8] - a[j + 10]; + x1i = a[j + 9] - a[j + 11]; + x2r = a[j + 12] + a[j + 14]; + x2i = a[j + 13] + a[j + 15]; + x3r = a[j + 12] - a[j + 14]; + x3i = a[j + 13] - a[j + 15]; + a[j + 8] = x0r + x2r; + a[j + 9] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j + 12] = -wk2i * x0r - wk2r * x0i; + a[j + 13] = -wk2i * x0i + wk2r * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j + 10] = wk1r * x0r - wk1i * x0i; + a[j + 11] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j + 14] = wk3r * x0r - wk3i * x0i; + a[j + 15] = wk3r * x0i + wk3i * x0r; + } + } + + private static void cftmdl(int n, int l, double[] a, double[] w) + { + int j, j1, j2, j3, k, k1, k2, m, m2; + double wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + m = l << 2; + for (j = 0; j < l; j += 2) + { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + a[j2] = x0r - x2r; + a[j2 + 1] = x0i - x2i; + a[j1] = x1r - x3i; + a[j1 + 1] = x1i + x3r; + a[j3] = x1r + x3i; + a[j3 + 1] = x1i - x3r; + } + wk1r = w[2]; + for (j = m; j < l + m; j += 2) + { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + a[j2] = x2i - x0i; + a[j2 + 1] = x0r - x2r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j1] = wk1r * (x0r - x0i); + a[j1 + 1] = wk1r * (x0r + x0i); + x0r = x3i + x1r; + x0i = x3r - x1i; + a[j3] = wk1r * (x0i - x0r); + a[j3 + 1] = wk1r * (x0i + x0r); + } + k1 = 0; + m2 = 2 * m; + for (k = m2; k < n; k += m2) + { + k1 += 2; + k2 = 2 * k1; + wk2r = w[k1]; + wk2i = w[k1 + 1]; + wk1r = w[k2]; + wk1i = w[k2 + 1]; + wk3r = wk1r - 2 * wk2i * wk1i; + wk3i = 2 * wk2i * wk1r - wk1i; + for (j = k; j < l + k; j += 2) + { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j2] = wk2r * x0r - wk2i * x0i; + a[j2 + 1] = wk2r * x0i + wk2i * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j1] = wk1r * x0r - wk1i * x0i; + a[j1 + 1] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j3] = wk3r * x0r - wk3i * x0i; + a[j3 + 1] = wk3r * x0i + wk3i * x0r; + } + wk1r = w[k2 + 2]; + wk1i = w[k2 + 3]; + wk3r = wk1r - 2 * wk2r * wk1i; + wk3i = 2 * wk2r * wk1r - wk1i; + for (j = k + m; j < l + (k + m); j += 2) + { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j2] = -wk2i * x0r - wk2r * x0i; + a[j2 + 1] = -wk2i * x0i + wk2r * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j1] = wk1r * x0r - wk1i * x0i; + a[j1 + 1] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j3] = wk3r * x0r - wk3i * x0i; + a[j3 + 1] = wk3r * x0i + wk3i * x0r; + } + } + } + + private static void rftfsub(int n, double[] a, int nc, double[] c, int nw) + { + int j, k, kk, ks, m; + double wkr, wki, xr, xi, yr, yi; + + m = n >> 1; + ks = 2 * nc / m; + kk = 0; + for (j = 2; j < m; j += 2) + { + k = n - j; + kk += ks; + wkr = 0.5 - c[nw + nc - kk]; + wki = c[nw + kk]; + xr = a[j] - a[k]; + xi = a[j + 1] + a[k + 1]; + yr = wkr * xr - wki * xi; + yi = wkr * xi + wki * xr; + a[j] -= yr; + a[j + 1] -= yi; + a[k] += yr; + a[k + 1] -= yi; + } + } + + private static void rftbsub(int n, double[] a, int nc, double[] c, int nw) + { + int j, k, kk, ks, m; + double wkr, wki, xr, xi, yr, yi; + + a[1] = -a[1]; + m = n >> 1; + ks = 2 * nc / m; + kk = 0; + for (j = 2; j < m; j += 2) + { + k = n - j; + kk += ks; + wkr = 0.5 - c[nw + nc - kk]; + wki = c[nw + kk]; + xr = a[j] - a[k]; + xi = a[j + 1] + a[k + 1]; + yr = wkr * xr + wki * xi; + yi = wkr * xi - wki * xr; + a[j] -= yr; + a[j + 1] = yi - a[j + 1]; + a[k] += yr; + a[k + 1] = yi - a[k + 1]; + } + a[m + 1] = -a[m + 1]; + } + } +} diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.cs index 7605d704e3..8beee67a4d 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Chip6510.cs @@ -218,7 +218,10 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS public void SyncState(Serializer ser) { + ser.BeginSection("Chip6510Cpu"); _cpu.SyncState(ser); + ser.EndSection(); + ser.Sync("_pinNmiLast", ref _pinNmiLast); ser.BeginSection("_port"); diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Registers.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Registers.cs index 61365f03e0..379b6a4fef 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Registers.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.Registers.cs @@ -21,16 +21,18 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS { addr &= 0x1F; var result = _databus; + switch (addr) { case 0x19: case 0x1A: case 0x1B: case 0x1C: - Flush(); + //Flush(); not needed result = ReadRegister(addr); break; } + return result; } @@ -125,6 +127,7 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS { addr &= 0x1F; _databus = val; + switch (addr) { case 0x19: @@ -137,7 +140,41 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS // can't write to these break; default: - Flush(); + + // we want to only flush the filter when the filter is actually changed, that way + // the FFT will not be impacted by small sample sizes from other changes + if (addr == 15 || addr == 16 || addr==17) + { + Flush(true); + } + else if (addr==18) + { + // note: we only want to flush the filter here if the filter components are changing + bool temp1 = (val & 0x10) != 0; + bool temp2 = (val & 0x20) != 0; + bool temp3 = (val & 0x40) != 0; + + if (temp1 != _filterSelectLoPass) + { + Flush(true); + } + else if (temp2 != _filterSelectBandPass) + { + Flush(true); + } + else if (temp3 != _filterSelectHiPass) + { + Flush(true); + } + else + { + Flush(false); + } + } + else + { + Flush(false); + } WriteRegister(addr, val); break; } @@ -168,12 +205,13 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS case 0x12: _voice2.Control = val; _envelope2.Gate = (val & 0x01) != 0; break; case 0x13: _envelope2.Attack = val >> 4; _envelope2.Decay = val & 0xF; break; case 0x14: _envelope2.Sustain = val >> 4; _envelope2.Release = val & 0xF; break; - case 0x15: _filterFrequency &= 0x3FF; _filterFrequency |= val & 0x7; break; + case 0x15: _filterFrequency &= 0x7F8; _filterFrequency |= val & 0x7; break; case 0x16: _filterFrequency &= 0x7; _filterFrequency |= val << 3; break; case 0x17: _filterEnable[0] = (val & 0x1) != 0; _filterEnable[1] = (val & 0x2) != 0; _filterEnable[2] = (val & 0x4) != 0; + _filterResonance = val >> 4; break; case 0x18: diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.SoundProvider.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.SoundProvider.cs index bb19ff969f..6f48ca52e2 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.SoundProvider.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.SoundProvider.cs @@ -37,7 +37,7 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS // There's not need to do this though unless this core wants to handle async in its own way (the client can handle these situations if not available from the core) private void GetSamples(short[] samples) { - Flush(); + Flush(true); var length = Math.Min(samples.Length, _outputBufferIndex); for (var i = 0; i < length; i++) { @@ -48,10 +48,46 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS public void GetSamplesSync(out short[] samples, out int nsamp) { - Flush(); + Flush(true); + + nsamp = _outputBufferIndex; + + for (int i = 0; i < _outputBufferIndex; i++) + { + _mixer = _outputBuffer_not_filtered[i] + _outputBuffer_filtered[i]; + _mixer = _mixer >> 7; + _mixer = (_mixer * _volume) >> 4; + _mixer -= _volume << 8; + + //Console.Write(_mixer); + //Console.Write(" "); + + if (_mixer > 0x7FFF) + { + _mixer = 0x7FFF; + } + + if (_mixer < -0x8000) + { + _mixer = -0x8000; + } + /* + if (_mixer < 0) + { + _mixer = 0; + } + */ + _outputBuffer[i * 2] = (short)_mixer; + _outputBuffer[i * 2 + 1] = (short)_mixer; + + } + //Console.WriteLine(" "); + //Console.WriteLine(" "); samples = _outputBuffer; - nsamp = _outputBufferIndex >> 1; + _outputBufferIndex = 0; + filter_index = 0; } + } } diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.cs index e561244749..ac17019b99 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/MOS/Sid.cs @@ -40,11 +40,15 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS private bool _filterSelectHiPass; private int _mixer; private readonly short[] _outputBuffer; + private int[] _outputBuffer_filtered; + private int[] _outputBuffer_not_filtered; private int _outputBufferIndex; + private int filter_index; + private int last_filtered_value; private int _potCounter; private int _potX; private int _potY; - private short _sample; + private int _sample; private int _voiceOutput0; private int _voiceOutput1; private int _voiceOutput2; @@ -57,6 +61,8 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS public Func ReadPotX; public Func ReadPotY; + public RealFFT fft; + private readonly int _cpuCyclesNum; private int _sampleCyclesNum; private readonly int _sampleCyclesDen; @@ -87,6 +93,8 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS _filterEnable[i] = false; _outputBuffer = new short[sampleRate]; + _outputBuffer_filtered = new int[sampleRate]; + _outputBuffer_not_filtered = new int[sampleRate]; } // ------------------------------------ @@ -119,8 +127,9 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS _potCounter--; } - public void Flush() + public void Flush(bool flush_filter) { + while (_cachedCycles > 0) { _cachedCycles--; @@ -145,35 +154,196 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.MOS _envelopeOutput1 = _envelope1.Level; _envelopeOutput2 = _envelope2.Level; + int temp_v0 = (_voiceOutput0 * _envelopeOutput0); + int temp_v1 = (_voiceOutput1 * _envelopeOutput1); + int temp_v2 = (_voiceOutput2 * _envelopeOutput2); + + int temp_filtered = 0; + int temp_not_filtered = 0; + + //note that voice 3 disable is relevent only if it is not going to the filter + // see block diargam http://archive.6502.org/datasheets/mos_6581_sid.pdf + if (!_filterEnable[2] && _disableVoice3) + temp_v2 = 0; + + // break sound into filtered and non-filtered output + // we need to process the filtered parts in bulk, so let's do it here + if (_filterEnable[0]) + temp_filtered += temp_v0; + else + temp_not_filtered += temp_v0; + + if (_filterEnable[1]) + temp_filtered += temp_v1; + else + temp_not_filtered += temp_v1; + + if (_filterEnable[2]) + temp_filtered += temp_v2; + else + temp_not_filtered += temp_v2; + _sampleCyclesNum += _sampleCyclesDen; if (_sampleCyclesNum >= _cpuCyclesNum) { _sampleCyclesNum -= _cpuCyclesNum; - _mixer = (_voiceOutput0 * _envelopeOutput0) >> 7; - _mixer += (_voiceOutput1 * _envelopeOutput1) >> 7; - _mixer += (_voiceOutput2 * _envelopeOutput2) >> 7; - _mixer = (_mixer * _volume) >> 4; - _mixer -= _volume << 8; - if (_mixer > 0x7FFF) - { - _mixer = 0x7FFF; - } - if (_mixer < -0x8000) - { - _mixer = -0x8000; - } - - _sample = unchecked((short)_mixer); if (_outputBufferIndex < _sampleRate) { - _outputBuffer[_outputBufferIndex++] = _sample; - _outputBuffer[_outputBufferIndex++] = _sample; + _outputBuffer_not_filtered[_outputBufferIndex] = temp_not_filtered; + _outputBuffer_filtered[_outputBufferIndex] = temp_filtered; + _outputBufferIndex++; } } } + //here we need to apply filtering to the samples and add them back to the buffer + + if (flush_filter) + { + if (_filterEnable[0] | _filterEnable[1] | _filterEnable[2]) + { + if ((_outputBufferIndex - filter_index) >= 16) + { + filter_operator(); + } + else + { + // the length is too short for the FFT to reliably act on the output + // instead, clamp it to the previous output. + for (int i = filter_index; i < _outputBufferIndex; i++) + { + _outputBuffer_filtered[i] = last_filtered_value; + } + } + } + + filter_index = _outputBufferIndex; + last_filtered_value = _outputBuffer_filtered[_outputBufferIndex - 1]; + } + + // if the filter is off, keep updating the filter index to the most recent Flush + if (!(_filterEnable[0] | _filterEnable[1] | _filterEnable[2])) + { + filter_index = _outputBufferIndex; + } } + + public void filter_operator() + { + double loc_filterFrequency = (double)(_filterFrequency << 2) + 500; + + double attenuation; + + int nsamp = _outputBufferIndex - filter_index; + + // pass the list of filtered samples to the FFT + // but needs to be a power of 2, so find the next highest power of 2 and re-sample + int nsamp_2 = 2; + bool test = true; + while(test) + { + nsamp_2 *= 2; + if (nsamp_2>nsamp) + { + test = false; + } + } + + fft = new RealFFT(nsamp_2); + + double[] temp_buffer = new double[nsamp_2]; + + // linearly interpolate the original sample set into the new denser sample set + for (double i = 0; i < nsamp_2; i++) + { + temp_buffer[(int)i] = _outputBuffer_filtered[(int)Math.Floor((i / (nsamp_2-1) * (nsamp - 1))) + filter_index]; + } + + /* + for (int i = 0; i< nsamp; i++) + { + Console.Write(_outputBuffer_filtered[(int)i + filter_index]); + Console.Write(" "); + } + + Console.WriteLine(" "); + Console.WriteLine("After"); + */ + + // now we have everything we need to perform the FFT + fft.ComputeForward(temp_buffer); + + // for each element in the frequency list, attenuate it according to the specs + for (int i = 0; i < nsamp_2; i++) + { + double freq = (i + 1) * ((double)(880*50)/nsamp); + + // add resonance effect + // let's assume that frequencies near the peak are doubled in strength at max resonance + if ((1.2 > freq / loc_filterFrequency) && (freq / loc_filterFrequency > 0.8 )) + { + temp_buffer[i] = temp_buffer[i] * (1 + (double)_filterResonance/15); + } + + // low pass filter + if (_filterSelectLoPass && freq > loc_filterFrequency) + { + //attenuated at 12db per octave + attenuation = Math.Log(freq / loc_filterFrequency, 2); + attenuation = 12 * attenuation; + temp_buffer[i] = temp_buffer[i] * Math.Pow(2, -attenuation / 10); + } + + // High pass filter + if (_filterSelectHiPass && freq < _filterFrequency) + { + //attenuated at 12db per octave + attenuation = Math.Log(freq / _filterFrequency, 2); + attenuation = 12 * attenuation; + temp_buffer[i] = temp_buffer[i] * Math.Pow(2, -attenuation / 10); + } + + // Band pass filter + if (_filterSelectBandPass) + { + //attenuated at 6db per octave + attenuation = Math.Log(freq / _filterFrequency, 2); + attenuation = 6 * attenuation; + temp_buffer[i] = temp_buffer[i] * Math.Pow(2, -Math.Abs(attenuation) / 10); + } + + } + + // now transform back into time space and reassemble the attenuated frequency components + fft.ComputeReverse(temp_buffer); + + int temp = nsamp - 1; + //re-sample back down to the original number of samples + for (double i = 0; i < nsamp; i++) + { + _outputBuffer_filtered[(int)i + filter_index] = (int)(temp_buffer[(int)Math.Ceiling((i / (nsamp - 1) * (nsamp_2 - 1)))]/(nsamp_2/2)); + + if (_outputBuffer_filtered[(int)i + filter_index] < 0) + { + _outputBuffer_filtered[(int)i + filter_index] = 0; + } + + // the FFT is only an approximate model and fails at low sample rates + // what we want to do is limit how much the output samples can deviate from previous output + // thus smoothing out the FT samples + + if (i<16) + _outputBuffer_filtered[(int)i + filter_index] = (int)((last_filtered_value * Math.Pow(15 - i,1) + _outputBuffer_filtered[(int)i + filter_index] * Math.Pow(i,1))/ Math.Pow(15,1)); + + //Console.Write(_outputBuffer_filtered[(int)i + filter_index]); + //Console.Write(" "); + } + + //Console.WriteLine(" "); + //Console.WriteLine("Before"); + + } // ---------------------------------- public void SyncState(Serializer ser) diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Tape.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Tape.cs index 7a05f7f67d..5bb981caf9 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Tape.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/Media/Tape.cs @@ -6,16 +6,16 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.Media { public class Tape { - private readonly byte[] _tapeData; + private readonly byte[] _tapeData; private readonly byte _version; - private readonly int _start; - private readonly int _end; + private readonly int _start; + private readonly int _end; - private int _pos; + private int _pos; - private int _cycle; + private int _cycle; - private bool _data; + private bool _data; public Tape(byte version, byte[] tapeData, int start, int end) { @@ -26,43 +26,43 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.Media Rewind(); } - public void ExecuteCycle() - { - if (_cycle == 0) - { - if (_pos >= _end) - { - _data = true; - return; - } + public void ExecuteCycle() + { + if (_cycle == 0) + { + if (_pos >= _end) + { + _data = true; + return; + } - _cycle = _tapeData[_pos++] * 8; - if (_cycle == 0) - { - if (_version == 0) - { - _cycle = 256 * 8; // unspecified overflow condition - } - else - { - _cycle = (int)(BitConverter.ToUInt32(_tapeData, _pos - 1) >> 8); - _pos += 3; - if (_cycle == 0) - { - throw new Exception("Bad tape data"); - } - } - } + _cycle = _tapeData[_pos++] * 8; + if (_cycle == 0) + { + if (_version == 0) + { + _cycle = 256 * 8; // unspecified overflow condition + } + else + { + _cycle = (int)(BitConverter.ToUInt32(_tapeData, _pos - 1) >> 8); + _pos += 3; + if (_cycle == 0) + { + throw new Exception("Bad tape data"); + } + } + } - _cycle++; - } + _cycle++; + } - // Send a single negative pulse at the end of a cycle - _data = --_cycle != 0; - } + // Send a single negative pulse at the end of a cycle + _data = --_cycle != 0; + } - // Rewinds the tape back to start - public void Rewind() + // Rewinds the tape back to start + public void Rewind() { _pos = _start; _cycle = 0; @@ -71,7 +71,7 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.Media // Reads from tape, this will tell the caller if the flag pin should be raised public bool Read() { - return _data; + return _data; } // Try to construct a tape file from file data. Returns null if not a tape file, throws exceptions for bad tape files. @@ -100,5 +100,8 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.Media ser.Sync("Cycle", ref _cycle); ser.Sync("Data", ref _data); } + + // Exposed for memory domains, should not be used for actual emulation implementation + public byte[] TapeDataDomain => _tapeData; } } diff --git a/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.cs b/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.cs index 5cffe9c019..8b1e60fc55 100644 --- a/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.cs +++ b/BizHawk.Emulation.Cores/Computers/Commodore64/Serial/Drive1541.cs @@ -65,13 +65,16 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.Serial ser.Sync("BitHistory", ref _bitHistory); ser.Sync("BitsRemainingInLatchedByte", ref _bitsRemainingInLatchedByte); ser.Sync("Sync", ref _sync); + ser.Sync("ByteReady", ref _byteReady); ser.Sync("DriveCpuClockNumerator", ref _driveCpuClockNum); ser.Sync("TrackNumber", ref _trackNumber); ser.Sync("MotorEnabled", ref _motorEnabled); ser.Sync("LedEnabled", ref _ledEnabled); ser.Sync("MotorStep", ref _motorStep); + ser.BeginSection("Disk6502"); _cpu.SyncState(ser); + ser.EndSection(); ser.Sync("RAM", ref _ram, useNull: false); @@ -86,6 +89,8 @@ namespace BizHawk.Emulation.Cores.Computers.Commodore64.Serial ser.Sync("SystemCpuClockNumerator", ref _cpuClockNum); ser.Sync("SystemDriveCpuRatioDifference", ref _ratioDifference); ser.Sync("DriveLightOffTime", ref _driveLightOffTime); + ser.Sync("TrackImageData", ref _trackImageData, useNull: false); + ser.Sync("DiskDensityCounter", ref _diskDensityCounter); ser.Sync("DiskSupplementaryCounter", ref _diskSupplementaryCounter); ser.Sync("DiskFluxReversalDetected", ref _diskFluxReversalDetected); diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IDebuggable.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IDebuggable.cs new file mode 100644 index 0000000000..45809e725e --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IDebuggable.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; + +using BizHawk.Emulation.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public partial class A7800Hawk : IDebuggable + { + public IDictionary GetCpuFlagsAndRegisters() + { + return new Dictionary + { + ["A"] = cpu.A, + ["X"] = cpu.X, + ["Y"] = cpu.Y, + ["S"] = cpu.S, + ["PC"] = cpu.PC, + ["Flag C"] = cpu.FlagC, + ["Flag Z"] = cpu.FlagZ, + ["Flag I"] = cpu.FlagI, + ["Flag D"] = cpu.FlagD, + ["Flag B"] = cpu.FlagB, + ["Flag V"] = cpu.FlagV, + ["Flag N"] = cpu.FlagN, + ["Flag T"] = cpu.FlagT + }; + } + + public void SetCpuRegister(string register, int value) + { + switch (register) + { + default: + throw new InvalidOperationException(); + case "A": + cpu.A = (byte)value; + break; + case "X": + cpu.X = (byte)value; + break; + case "Y": + cpu.Y = (byte)value; + break; + case "S": + cpu.S = (byte)value; + break; + case "PC": + cpu.PC = (ushort)value; + break; + case "Flag I": + cpu.FlagI = value > 0; + break; + } + } + + public IMemoryCallbackSystem MemoryCallbacks + { + [FeatureNotImplemented] + get { throw new NotImplementedException(); } + } + + public bool CanStep(StepType type) + { + return false; + } + + [FeatureNotImplemented] + public void Step(StepType type) + { + throw new NotImplementedException(); + } + + public int TotalExecutedCycles + { + get { return cpu.TotalExecutedCycles; } + } + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IEmulator.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IEmulator.cs new file mode 100644 index 0000000000..c739349520 --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IEmulator.cs @@ -0,0 +1,74 @@ +using BizHawk.Emulation.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public partial class A7800Hawk : IEmulator + { + public IEmulatorServiceProvider ServiceProvider { get; } + + public ControllerDefinition ControllerDefinition { get; private set; } + + //Maria related variables + public int cycle; + public int cpu_cycle; + public int scanline; + + public void FrameAdvance(IController controller, bool render, bool rendersound) + { + _frame++; + + if (controller.IsPressed("Power")) + { + // it seems that theMachine.Reset() doesn't clear ram, etc + // this should leave hsram intact but clear most other things + HardReset(); + } + + if (_islag) + { + _lagcount++; + } + + scanline = 0; + + // actually execute the frame + while (scanline < 263) + { + maria.Execute(cycle, scanline); + cycle++; + cpu_cycle++; + + + if (cycle == 454) + { + scanline++; + cycle = 0; + } + } + + + } + + public int Frame => _frame; + + public string SystemId => "A7800"; + + public bool DeterministicEmulation { get; set; } + + public void ResetCounters() + { + _frame = 0; + _lagcount = 0; + _islag = false; + } + + public CoreComm CoreComm { get; } + + public void Dispose() + { + maria = null; + tia = null; + m6532 = null; + } + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IInputPollable.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IInputPollable.cs new file mode 100644 index 0000000000..f2c5b97360 --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IInputPollable.cs @@ -0,0 +1,24 @@ +using BizHawk.Emulation.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public partial class A7800Hawk : IInputPollable + { + public int LagCount + { + get { return _lagcount; } + set { _lagcount = value; } + } + + public bool IsLagFrame + { + get { return _islag; } + set { _islag = value; } + } + + public IInputCallbackSystem InputCallbacks { get; } = new InputCallbackSystem(); + + private bool _islag = true; + private int _lagcount; + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IMemoryDomains.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IMemoryDomains.cs new file mode 100644 index 0000000000..3d7d86a4f4 --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IMemoryDomains.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; + +using BizHawk.Emulation.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public partial class A7800Hawk + { + private IMemoryDomains MemoryDomains; + + public void SetupMemoryDomains() + { + var domains = new List + { + new MemoryDomainDelegate( + "Main RAM", + RAM.Length, + MemoryDomain.Endian.Little, + addr => RAM[addr], + (addr, value) => RAM[addr] = value, + 1), + new MemoryDomainDelegate( + "TIA Registers", + TIA_regs.Length, + MemoryDomain.Endian.Little, + addr => TIA_regs[addr], + (addr, value) => TIA_regs[addr] = value, + 1), + new MemoryDomainDelegate( + "Maria Registers", + Maria_regs.Length, + MemoryDomain.Endian.Little, + addr => Maria_regs[addr], + (addr, value) => Maria_regs[addr] = value, + 1), + new MemoryDomainDelegate( + "6532 Registers", + regs_6532.Length, + MemoryDomain.Endian.Little, + addr => regs_6532[addr], + (addr, value) => regs_6532[addr] = value, + 1), + new MemoryDomainDelegate( + "Ram Block 0", + 0xB0, + MemoryDomain.Endian.Little, + addr => RAM[addr-0x840], + (addr, value) => RAM[addr-0x840] = value, + 1 + ), + new MemoryDomainDelegate( + "Ram Block 1", + 0xB0, + MemoryDomain.Endian.Little, + addr => RAM[addr-0x940], + (addr, value) => RAM[addr-0x940] = value, + 1 + ), + new MemoryDomainDelegate( + "System Bus", + 0X10000, + MemoryDomain.Endian.Little, + addr => PeekSystemBus(addr), + (addr, value) => PokeSystemBus(addr, value), + 1 + ) + }; + + MemoryDomains = new MemoryDomainList(domains); + (ServiceProvider as BasicServiceProvider).Register(MemoryDomains); + } + + private byte PeekSystemBus(long addr) + { + ushort addr2 = (ushort)(addr & 0xFFFF); + return ReadMemory(addr2); + } + + private void PokeSystemBus(long addr, byte value) + { + ushort addr2 = (ushort)(addr & 0xFFFF); + WriteMemory(addr2, value); + } + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISaveRam.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISaveRam.cs new file mode 100644 index 0000000000..b3a08cde2b --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.ISaveRam.cs @@ -0,0 +1,26 @@ +using System; +using BizHawk.Emulation.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public partial class A7800Hawk : ISaveRam + { + public byte[] CloneSaveRam() + { + return (byte[])_hsram.Clone(); + } + + public void StoreSaveRam(byte[] data) + { + Buffer.BlockCopy(data, 0, _hsram, 0, data.Length); + } + + public bool SaveRamModified + { + get + { + return false; + } + } + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IStatable.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IStatable.cs new file mode 100644 index 0000000000..96356abb5b --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.IStatable.cs @@ -0,0 +1,59 @@ +using System.IO; + +using BizHawk.Common; +using BizHawk.Emulation.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public partial class A7800Hawk : IStatable + { + public bool BinarySaveStatesPreferred => true; + + public void SaveStateText(TextWriter writer) + { + SyncState(new Serializer(writer)); + } + + public void LoadStateText(TextReader reader) + { + SyncState(new Serializer(reader)); + } + + public void SaveStateBinary(BinaryWriter bw) + { + SyncState(new Serializer(bw)); + } + + public void LoadStateBinary(BinaryReader br) + { + SyncState(new Serializer(br)); + } + + public byte[] SaveStateBinary() + { + MemoryStream ms = new MemoryStream(); + BinaryWriter bw = new BinaryWriter(ms); + SaveStateBinary(bw); + bw.Flush(); + return ms.ToArray(); + } + + private void SyncState(Serializer ser) + { + byte[] core = null; + if (ser.IsWriter) + { + var ms = new MemoryStream(); + ms.Close(); + core = ms.ToArray(); + } + + ser.BeginSection("Atari7800"); + ser.Sync("core", ref core, false); + ser.Sync("Lag", ref _lagcount); + ser.Sync("Frame", ref _frame); + ser.Sync("IsLag", ref _islag); + ser.EndSection(); + } + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs new file mode 100644 index 0000000000..1ea8b6aea8 --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800Hawk.cs @@ -0,0 +1,323 @@ +using System; + +using BizHawk.Common.BufferExtensions; +using BizHawk.Emulation.Common; +using BizHawk.Emulation.Cores.Components.M6502; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + [CoreAttributes( + "A7800Hawk", + "", + isPorted: false, + isReleased: true)] + [ServiceNotApplicable(typeof(ISettable<,>), typeof(IDriveLight))] + public partial class A7800Hawk : IEmulator, ISaveRam, IDebuggable, IStatable, IInputPollable, IRegionable + { + // this register selects between 2600 and 7800 mode in the A7800 + // however, we already have a 2600 emulator so this core will only be loading A7800 games + // furthermore, the location of the register is in the same place as TIA registers (0x0-0x1F) + // any writes to this location before the register is 'locked' will go to the register and not the TIA + public byte A7800_control_register; + + // memory domains + public byte[] TIA_regs = new byte[0x20]; + public byte[] Maria_regs = new byte[0x20]; + public byte[] RAM = new byte[0x1000]; + public byte[] regs_6532 = new byte[0x80]; + + private readonly byte[] _rom; + private readonly byte[] _hsbios; + private readonly byte[] _bios; + private readonly byte[] _hsram = new byte[2048]; + + private int _frame = 0; + + public MOS6502X cpu; + public Maria maria; + private bool _isPAL; + public M6532 m6532; + public TIA tia; + + public A7800Hawk(CoreComm comm, GameInfo game, byte[] rom, string gameDbFn) + { + var ser = new BasicServiceProvider(this); + + maria = new Maria(); + tia = new TIA(); + + ser.Register(maria); + ser.Register(tia); + ServiceProvider = ser; + + maria = new Maria + { + ReadMemory = ReadMemory + }; + + CoreComm = comm; + byte[] highscoreBios = comm.CoreFileProvider.GetFirmware("A78", "Bios_HSC", false, "Some functions may not work without the high score BIOS."); + byte[] palBios = comm.CoreFileProvider.GetFirmware("A78", "Bios_PAL", false, "The game will not run if the correct region BIOS is not available."); + byte[] ntscBios = comm.CoreFileProvider.GetFirmware("A78", "Bios_NTSC", false, "The game will not run if the correct region BIOS is not available."); + + if (rom.Length % 1024 == 128) + { + Console.WriteLine("Trimming 128 byte .a78 header..."); + byte[] newrom = new byte[rom.Length - 128]; + Buffer.BlockCopy(rom, 128, newrom, 0, newrom.Length); + rom = newrom; + } + + _isPAL = false; + + // look up hash in gamedb to see what mapper to use + // if none found default is zero + // also check for PAL region + string hash_md5 = null; + string s_mapper = null; + hash_md5 = "md5:" + rom.HashMD5(0, rom.Length); + + var gi = Database.CheckDatabase(hash_md5); + + if (gi != null) + { + var dict = gi.GetOptionsDict(); + if (!dict.ContainsKey("PAL")) + { + _isPAL = true; + } + if (!dict.ContainsKey("board")) + { + s_mapper = dict["board"]; + } + else + throw new Exception("No Board selected for this mapper"); + } + else + { + throw new Exception("ROM not in gamedb"); + } + + _rom = rom; + _hsbios = highscoreBios; + _bios = _isPAL ? palBios : ntscBios; + + if (_bios == null) + { + throw new MissingFirmwareException("The BIOS corresponding to the region of the game you loaded is required to run Atari 7800 games."); + } + + // set up palette and frame rate + if (_isPAL) + { + maria._frameHz = 50; + maria._palette = PALPalette; + } + else + { + maria._frameHz = 60; + maria._palette = NTSCPalette; + } + + + HardReset(); + } + + public DisplayType Region => _isPAL ? DisplayType.PAL : DisplayType.NTSC; + + public A7800HawkControl ControlAdapter { get; private set; } + + private void HardReset() + { + A7800_control_register = 0; + + tia.Reset(); + cpu.Reset(); + cpu.SetCallbacks(ReadMemory, ReadMemory, ReadMemory, WriteMemory); + + maria.Reset(); + m6532 = new M6532(); + + TIA_regs = new byte[0x20]; + Maria_regs = new byte[0x20]; + RAM = new byte[0x1000]; + regs_6532 = new byte[0x80]; + } + + /* + * MariaTables.cs + * + * Palette tables for the Maria class. + * All derived from Dan Boris' 7800/MAME code. + * + * Copyright © 2004 Mike Murphy + * + */ + + public static readonly int[] NTSCPalette = + { + 0x000000, 0x1c1c1c, 0x393939, 0x595959, // Grey + 0x797979, 0x929292, 0xababab, 0xbcbcbc, + 0xcdcdcd, 0xd9d9d9, 0xe6e6e6, 0xececec, + 0xf2f2f2, 0xf8f8f8, 0xffffff, 0xffffff, + + 0x391701, 0x5e2304, 0x833008, 0xa54716, // Gold + 0xc85f24, 0xe37820, 0xff911d, 0xffab1d, + 0xffc51d, 0xffce34, 0xffd84c, 0xffe651, + 0xfff456, 0xfff977, 0xffff98, 0xffff98, + + 0x451904, 0x721e11, 0x9f241e, 0xb33a20, // Orange + 0xc85122, 0xe36920, 0xff811e, 0xff8c25, + 0xff982c, 0xffae38, 0xffc545, 0xffc559, + 0xffc66d, 0xffd587, 0xffe4a1, 0xffe4a1, + + 0x4a1704, 0x7e1a0d, 0xb21d17, 0xc82119, // Red Orange + 0xdf251c, 0xec3b38, 0xfa5255, 0xfc6161, + 0xff706e, 0xff7f7e, 0xff8f8f, 0xff9d9e, + 0xffabad, 0xffb9bd, 0xffc7ce, 0xffc7ce, + + 0x050568, 0x3b136d, 0x712272, 0x8b2a8c, // Pink + 0xa532a6, 0xb938ba, 0xcd3ecf, 0xdb47dd, + 0xea51eb, 0xf45ff5, 0xfe6dff, 0xfe7afd, + 0xff87fb, 0xff95fd, 0xffa4ff, 0xffa4ff, + + 0x280479, 0x400984, 0x590f90, 0x70249d, // Purple + 0x8839aa, 0xa441c3, 0xc04adc, 0xd054ed, + 0xe05eff, 0xe96dff, 0xf27cff, 0xf88aff, + 0xff98ff, 0xfea1ff, 0xfeabff, 0xfeabff, + + 0x35088a, 0x420aad, 0x500cd0, 0x6428d0, // Purple Blue + 0x7945d0, 0x8d4bd4, 0xa251d9, 0xb058ec, + 0xbe60ff, 0xc56bff, 0xcc77ff, 0xd183ff, + 0xd790ff, 0xdb9dff, 0xdfaaff, 0xdfaaff, + + 0x051e81, 0x0626a5, 0x082fca, 0x263dd4, // Blue1 + 0x444cde, 0x4f5aee, 0x5a68ff, 0x6575ff, + 0x7183ff, 0x8091ff, 0x90a0ff, 0x97a9ff, + 0x9fb2ff, 0xafbeff, 0xc0cbff, 0xc0cbff, + + 0x0c048b, 0x2218a0, 0x382db5, 0x483ec7, // Blue2 + 0x584fda, 0x6159ec, 0x6b64ff, 0x7a74ff, + 0x8a84ff, 0x918eff, 0x9998ff, 0xa5a3ff, + 0xb1aeff, 0xb8b8ff, 0xc0c2ff, 0xc0c2ff, + + 0x1d295a, 0x1d3876, 0x1d4892, 0x1c5cac, // Light Blue + 0x1c71c6, 0x3286cf, 0x489bd9, 0x4ea8ec, + 0x55b6ff, 0x70c7ff, 0x8cd8ff, 0x93dbff, + 0x9bdfff, 0xafe4ff, 0xc3e9ff, 0xc3e9ff, + + 0x2f4302, 0x395202, 0x446103, 0x417a12, // Turquoise + 0x3e9421, 0x4a9f2e, 0x57ab3b, 0x5cbd55, + 0x61d070, 0x69e27a, 0x72f584, 0x7cfa8d, + 0x87ff97, 0x9affa6, 0xadffb6, 0xadffb6, + + 0x0a4108, 0x0d540a, 0x10680d, 0x137d0f, // Green Blue + 0x169212, 0x19a514, 0x1cb917, 0x1ec919, + 0x21d91b, 0x47e42d, 0x6ef040, 0x78f74d, + 0x83ff5b, 0x9aff7a, 0xb2ff9a, 0xb2ff9a, + + 0x04410b, 0x05530e, 0x066611, 0x077714, // Green + 0x088817, 0x099b1a, 0x0baf1d, 0x48c41f, + 0x86d922, 0x8fe924, 0x99f927, 0xa8fc41, + 0xb7ff5b, 0xc9ff6e, 0xdcff81, 0xdcff81, + + 0x02350f, 0x073f15, 0x0c4a1c, 0x2d5f1e, // Yellow Green + 0x4f7420, 0x598324, 0x649228, 0x82a12e, + 0xa1b034, 0xa9c13a, 0xb2d241, 0xc4d945, + 0xd6e149, 0xe4f04e, 0xf2ff53, 0xf2ff53, + + 0x263001, 0x243803, 0x234005, 0x51541b, // Orange Green + 0x806931, 0x978135, 0xaf993a, 0xc2a73e, + 0xd5b543, 0xdbc03d, 0xe1cb38, 0xe2d836, + 0xe3e534, 0xeff258, 0xfbff7d, 0xfbff7d, + + 0x401a02, 0x581f05, 0x702408, 0x8d3a13, // Light Orange + 0xab511f, 0xb56427, 0xbf7730, 0xd0853a, + 0xe19344, 0xeda04e, 0xf9ad58, 0xfcb75c, + 0xffc160, 0xffc671, 0xffcb83, 0xffcb83 + }; + + public static readonly int[] PALPalette = + { + 0x000000, 0x1c1c1c, 0x393939, 0x595959, // Grey + 0x797979, 0x929292, 0xababab, 0xbcbcbc, + 0xcdcdcd, 0xd9d9d9, 0xe6e6e6, 0xececec, + 0xf2f2f2, 0xf8f8f8, 0xffffff, 0xffffff, + + 0x263001, 0x243803, 0x234005, 0x51541b, // Orange Green + 0x806931, 0x978135, 0xaf993a, 0xc2a73e, + 0xd5b543, 0xdbc03d, 0xe1cb38, 0xe2d836, + 0xe3e534, 0xeff258, 0xfbff7d, 0xfbff7d, + + 0x263001, 0x243803, 0x234005, 0x51541b, // Orange Green + 0x806931, 0x978135, 0xaf993a, 0xc2a73e, + 0xd5b543, 0xdbc03d, 0xe1cb38, 0xe2d836, + 0xe3e534, 0xeff258, 0xfbff7d, 0xfbff7d, + + 0x401a02, 0x581f05, 0x702408, 0x8d3a13, // Light Orange + 0xab511f, 0xb56427, 0xbf7730, 0xd0853a, + 0xe19344, 0xeda04e, 0xf9ad58, 0xfcb75c, + 0xffc160, 0xffc671, 0xffcb83, 0xffcb83, + + 0x391701, 0x5e2304, 0x833008, 0xa54716, // Gold + 0xc85f24, 0xe37820, 0xff911d, 0xffab1d, + 0xffc51d, 0xffce34, 0xffd84c, 0xffe651, + 0xfff456, 0xfff977, 0xffff98, 0xffff98, + + 0x451904, 0x721e11, 0x9f241e, 0xb33a20, // Orange + 0xc85122, 0xe36920, 0xff811e, 0xff8c25, + 0xff982c, 0xffae38, 0xffc545, 0xffc559, + 0xffc66d, 0xffd587, 0xffe4a1, 0xffe4a1, + + 0x4a1704, 0x7e1a0d, 0xb21d17, 0xc82119, // Red Orange + 0xdf251c, 0xec3b38, 0xfa5255, 0xfc6161, + 0xff706e, 0xff7f7e, 0xff8f8f, 0xff9d9e, + 0xffabad, 0xffb9bd, 0xffc7ce, 0xffc7ce, + + 0x050568, 0x3b136d, 0x712272, 0x8b2a8c, // Pink + 0xa532a6, 0xb938ba, 0xcd3ecf, 0xdb47dd, + 0xea51eb, 0xf45ff5, 0xfe6dff, 0xfe7afd, + 0xff87fb, 0xff95fd, 0xffa4ff, 0xffa4ff, + + 0x280479, 0x400984, 0x590f90, 0x70249d, // Purple + 0x8839aa, 0xa441c3, 0xc04adc, 0xd054ed, + 0xe05eff, 0xe96dff, 0xf27cff, 0xf88aff, + 0xff98ff, 0xfea1ff, 0xfeabff, 0xfeabff, + + 0x051e81, 0x0626a5, 0x082fca, 0x263dd4, // Blue1 + 0x444cde, 0x4f5aee, 0x5a68ff, 0x6575ff, + 0x7183ff, 0x8091ff, 0x90a0ff, 0x97a9ff, + 0x9fb2ff, 0xafbeff, 0xc0cbff, 0xc0cbff, + + 0x0c048b, 0x2218a0, 0x382db5, 0x483ec7, // Blue2 + 0x584fda, 0x6159ec, 0x6b64ff, 0x7a74ff, + 0x8a84ff, 0x918eff, 0x9998ff, 0xa5a3ff, + 0xb1aeff, 0xb8b8ff, 0xc0c2ff, 0xc0c2ff, + + 0x1d295a, 0x1d3876, 0x1d4892, 0x1c5cac, // Light Blue + 0x1c71c6, 0x3286cf, 0x489bd9, 0x4ea8ec, + 0x55b6ff, 0x70c7ff, 0x8cd8ff, 0x93dbff, + 0x9bdfff, 0xafe4ff, 0xc3e9ff, 0xc3e9ff, + + 0x2f4302, 0x395202, 0x446103, 0x417a12, // Turquoise + 0x3e9421, 0x4a9f2e, 0x57ab3b, 0x5cbd55, + 0x61d070, 0x69e27a, 0x72f584, 0x7cfa8d, + 0x87ff97, 0x9affa6, 0xadffb6, 0xadffb6, + + 0x0a4108, 0x0d540a, 0x10680d, 0x137d0f, // Green Blue + 0x169212, 0x19a514, 0x1cb917, 0x1ec919, + 0x21d91b, 0x47e42d, 0x6ef040, 0x78f74d, + 0x83ff5b, 0x9aff7a, 0xb2ff9a, 0xb2ff9a, + + 0x04410b, 0x05530e, 0x066611, 0x077714, // Green + 0x088817, 0x099b1a, 0x0baf1d, 0x48c41f, + 0x86d922, 0x8fe924, 0x99f927, 0xa8fc41, + 0xb7ff5b, 0xc9ff6e, 0xdcff81, 0xdcff81, + + 0x02350f, 0x073f15, 0x0c4a1c, 0x2d5f1e, // Yellow Green + 0x4f7420, 0x598324, 0x649228, 0x82a12e, + 0xa1b034, 0xa9c13a, 0xb2d241, 0xc4d945, + 0xd6e149, 0xe4f04e, 0xf2ff53, 0xf2ff53 + }; + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControl.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControl.cs new file mode 100644 index 0000000000..ddb0815b14 --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/A7800HawkControl.cs @@ -0,0 +1,409 @@ +using System; + +using EMU7800.Core; +using BizHawk.Emulation.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public class A7800HawkControl + { + private static readonly ControllerDefinition Joystick = new ControllerDefinition + { + Name = "Atari 7800 Joystick Controller", + BoolButtons = + { + // hard reset, not passed to EMU7800 + "Power", + + // on the console + "Reset", + "Select", + "BW", // should be "Color"?? + "Left Difficulty", // better not put P# on these as they might not correspond to player numbers + "Right Difficulty", + + // ports + "P1 Up", "P1 Down", "P1 Left", "P1 Right", "P1 Trigger", + "P2 Up", "P2 Down", "P2 Left", "P2 Right", "P2 Trigger" + } + }; + + private static readonly ControllerDefinition Paddles = new ControllerDefinition + { + Name = "Atari 7800 Paddle Controller", + BoolButtons = + { + // hard reset, not passed to EMU7800 + "Power", + + // on the console + "Reset", + "Select", + "BW", // should be "Color"?? + "Left Difficulty", // better not put P# on these as they might not correspond to player numbers + "Right Difficulty", + + // ports + "P1 Trigger", + "P2 Trigger", + "P3 Trigger", + "P4 Trigger" + }, + FloatControls = // should be in [0..700000] + { + "P1 Paddle", + "P2 Paddle", + "P3 Paddle", + "P4 Paddle" + }, + FloatRanges = + { + // what is the center point supposed to be here? + new[] { 0.0f, 0.0f, 700000.0f }, + new[] { 0.0f, 0.0f, 700000.0f }, + new[] { 0.0f, 0.0f, 700000.0f }, + new[] { 0.0f, 0.0f, 700000.0f } + } + }; + + private static readonly ControllerDefinition Keypad = new ControllerDefinition + { + Name = "Atari 7800 Keypad Controller", + BoolButtons = + { + // hard reset, not passed to EMU7800 + "Power", + + // on the console + "Reset", + "Select", + "BW", // should be "Color"?? + "Toggle Left Difficulty", // better not put P# on these as they might not correspond to player numbers + "Toggle Right Difficulty", + + // ports + "P1 Keypad1", "P1 Keypad2", "P1 Keypad3", + "P1 Keypad4", "P1 Keypad5", "P1 Keypad6", + "P1 Keypad7", "P1 Keypad8", "P1 Keypad9", + "P1 KeypadA", "P1 Keypad0", "P1 KeypadP", + "P2 Keypad1", "P2 Keypad2", "P2 Keypad3", + "P2 Keypad4", "P2 Keypad5", "P2 Keypad6", + "P2 Keypad7", "P2 Keypad8", "P2 Keypad9", + "P2 KeypadA", "P2 Keypad0", "P2 KeypadP", + "P3 Keypad1", "P3 Keypad2", "P3 Keypad3", + "P3 Keypad4", "P3 Keypad5", "P3 Keypad6", + "P3 Keypad7", "P3 Keypad8", "P3 Keypad9", + "P3 KeypadA", "P3 Keypad0", "P3 KeypadP", + "P4 Keypad1", "P4 Keypad2", "P4 Keypad3", + "P4 Keypad4", "P4 Keypad5", "P4 Keypad6", + "P4 Keypad7", "P4 Keypad8", "P4 Keypad9", + "P4 KeypadA", "P4 Keypad0", "P4 KeypadP" + } + }; + + private static readonly ControllerDefinition Driving = new ControllerDefinition + { + Name = "Atari 7800 Driving Controller", + BoolButtons = + { + // hard reset, not passed to EMU7800 + "Power", + + // on the console + "Reset", + "Select", + "BW", // should be "Color"?? + "Toggle Left Difficulty", // better not put P# on these as they might not correspond to player numbers + "Toggle Right Difficulty", + + // ports + "P1 Trigger", + "P2 Trigger" + }, + FloatControls = // should be in [0..3] + { + "P1 Driving", + "P2 Driving" + }, + FloatRanges = + { + new[] { 0.0f, 0.0f, 3.0f }, + new[] { 0.0f, 0.0f, 3.0f }, + new[] { 0.0f, 0.0f, 3.0f } + } + }; + + private static readonly ControllerDefinition BoosterGrip = new ControllerDefinition + { + Name = "Atari 7800 Booster Grip Controller", + BoolButtons = + { + // hard reset, not passed to EMU7800 + "Power", + + // on the console + "Reset", + "Select", + "BW", // should be "Color"?? + "Toggle Left Difficulty", // better not put P# on these as they might not correspond to player numbers + "Toggle Right Difficulty", + + // ports + // NB: as referenced by the emu, p1t2 = p1t2, p1t3 = p2t2, p2t2 = p3t2, p2t3 = p4t2 + "P1 Up", "P1 Down", "P1 Left", "P1 Right", "P1 Trigger", "P1 Trigger 2", "P1 Trigger 3", + "P2 Up", "P2 Down", "P2 Left", "P2 Right", "P2 Trigger", "P2 Trigger 2", "P2 Trigger 3" + } + }; + + private static readonly ControllerDefinition ProLineJoystick = new ControllerDefinition + { + Name = "Atari 7800 ProLine Joystick Controller", + BoolButtons = + { + // hard reset, not passed to EMU7800 + "Power", + + // on the console + "Reset", + "Select", + "Pause", + "Toggle Left Difficulty", // better not put P# on these as they might not correspond to player numbers + "Toggle Right Difficulty", + + // ports + "P1 Up", "P1 Down", "P1 Left", "P1 Right", "P1 Trigger", "P1 Trigger 2", + "P2 Up", "P2 Down", "P2 Left", "P2 Right", "P2 Trigger", "P2 Trigger 2" + } + }; + + private static readonly ControllerDefinition Lightgun = new ControllerDefinition + { + Name = "Atari 7800 Light Gun Controller", + BoolButtons = + { + // hard reset, not passed to EMU7800 + "Power", + + // on the console + "Reset", + "Select", + "Pause", + "Left Difficulty", // better not put P# on these as they might not correspond to player numbers + "Right Difficulty", + + // ports + "P1 Trigger", + "P2 Trigger" + }, + FloatControls = // vpos should be actual scanline number. hpos should be in [0..319]?? + { + "P1 VPos", "P1 HPos", + "P2 VPos", "P2 HPos" + }, + FloatRanges = + { + // how many scanlines are there again?? + new[] { 0.0f, 0.0f, 240.0f }, + new[] { 0.0f, 0.0f, 319.0f }, + new[] { 0.0f, 0.0f, 240.0f }, + new[] { 0.0f, 0.0f, 319.0f } + } + }; + + private struct ControlAdapter + { + public readonly ControllerDefinition Type; + public readonly Controller Left; + public readonly Controller Right; + public readonly Action Convert; + + public ControlAdapter(ControllerDefinition type, Controller left, Controller right, Action convert) + { + Type = type; + Left = left; + Right = right; + Convert = convert; + } + } + + private static readonly ControlAdapter[] Adapters = + { + new ControlAdapter(Joystick, Controller.Joystick, Controller.Joystick, ConvertJoystick), + new ControlAdapter(Paddles, Controller.Paddles, Controller.Paddles, ConvertPaddles), + new ControlAdapter(Keypad, Controller.Keypad, Controller.Keypad, ConvertKeypad), + new ControlAdapter(Driving, Controller.Driving, Controller.Driving, ConvertDriving), + new ControlAdapter(BoosterGrip, Controller.BoosterGrip, Controller.BoosterGrip, ConvertBoosterGrip), + new ControlAdapter(ProLineJoystick, Controller.ProLineJoystick, Controller.ProLineJoystick, ConvertProLineJoystick), + new ControlAdapter(Lightgun, Controller.Lightgun, Controller.Lightgun, ConvertLightgun), + }; + + private static void ConvertConsoleButtons(IController c, InputState s) + { + s.RaiseInput(0, MachineInput.Reset, c.IsPressed("Reset")); + s.RaiseInput(0, MachineInput.Select, c.IsPressed("Select")); + s.RaiseInput(0, MachineInput.Color, c.IsPressed("BW")); + if (c.IsPressed("Toggle Left Difficulty")) + { + s.RaiseInput(0, MachineInput.LeftDifficulty, c.IsPressed("Toggle Left Difficulty")); + } + + if (c.IsPressed("Toggle Right Difficulty")) + { + s.RaiseInput(0, MachineInput.RightDifficulty, c.IsPressed("Toggle Right Difficulty")); + } + } + + private static void ConvertConsoleButtons7800(IController c, InputState s) + { + s.RaiseInput(0, MachineInput.Reset, c.IsPressed("Reset")); + s.RaiseInput(0, MachineInput.Select, c.IsPressed("Select")); + s.RaiseInput(0, MachineInput.Color, c.IsPressed("Pause")); + if (c.IsPressed("Toggle Left Difficulty")) + { + s.RaiseInput(0, MachineInput.LeftDifficulty, c.IsPressed("Toggle Left Difficulty")); + } + + if (c.IsPressed("Toggle Right Difficulty")) + { + s.RaiseInput(0, MachineInput.RightDifficulty, c.IsPressed("Toggle Right Difficulty")); + } + } + + private static void ConvertDirections(IController c, InputState s, int p) + { + string ps = $"P{p + 1} "; + s.RaiseInput(p, MachineInput.Up, c.IsPressed(ps + "Up")); + s.RaiseInput(p, MachineInput.Down, c.IsPressed(ps + "Down")); + s.RaiseInput(p, MachineInput.Left, c.IsPressed(ps + "Left")); + s.RaiseInput(p, MachineInput.Right, c.IsPressed(ps + "Right")); + } + + private static void ConvertTrigger(IController c, InputState s, int p) + { + string ps = $"P{p + 1} "; + s.RaiseInput(p, MachineInput.Fire, c.IsPressed(ps + "Trigger")); + } + + private static void ConvertJoystick(IController c, InputState s) + { + s.ClearControllerInput(); + ConvertConsoleButtons(c, s); + ConvertDirections(c, s, 0); + ConvertDirections(c, s, 1); + ConvertTrigger(c, s, 0); + ConvertTrigger(c, s, 1); + } + + private static void ConvertPaddles(IController c, InputState s) + { + s.ClearControllerInput(); + ConvertConsoleButtons(c, s); + for (int i = 0; i < 4; i++) + { + string ps = $"P{i + 1} "; + ConvertTrigger(c, s, i); + s.RaisePaddleInput(i, 700000, (int)c.GetFloat(ps + "Trigger")); + } + } + + private static void ConvertKeypad(IController c, InputState s) + { + s.ClearControllerInput(); + ConvertConsoleButtons(c, s); + for (int i = 0; i < 4; i++) + { + string ps = $"P{i + 1} "; + s.RaiseInput(i, MachineInput.NumPad1, c.IsPressed(ps + "Keypad1")); + s.RaiseInput(i, MachineInput.NumPad2, c.IsPressed(ps + "Keypad2")); + s.RaiseInput(i, MachineInput.NumPad3, c.IsPressed(ps + "Keypad3")); + s.RaiseInput(i, MachineInput.NumPad4, c.IsPressed(ps + "Keypad4")); + s.RaiseInput(i, MachineInput.NumPad5, c.IsPressed(ps + "Keypad5")); + s.RaiseInput(i, MachineInput.NumPad6, c.IsPressed(ps + "Keypad6")); + s.RaiseInput(i, MachineInput.NumPad7, c.IsPressed(ps + "Keypad7")); + s.RaiseInput(i, MachineInput.NumPad8, c.IsPressed(ps + "Keypad8")); + s.RaiseInput(i, MachineInput.NumPad9, c.IsPressed(ps + "Keypad9")); + s.RaiseInput(i, MachineInput.NumPadMult, c.IsPressed(ps + "KeypadA")); + s.RaiseInput(i, MachineInput.NumPad0, c.IsPressed(ps + "Keypad0")); + s.RaiseInput(i, MachineInput.NumPadHash, c.IsPressed(ps + "KeypadP")); + } + } + + private static readonly MachineInput[] Drvlut = + { + MachineInput.Driving0, + MachineInput.Driving1, + MachineInput.Driving2, + MachineInput.Driving3 + }; + + private static void ConvertDriving(IController c, InputState s) + { + s.ClearControllerInput(); + ConvertConsoleButtons(c, s); + ConvertTrigger(c, s, 0); + ConvertTrigger(c, s, 1); + s.RaiseInput(0, Drvlut[(int)c.GetFloat("P1 Driving")], true); + s.RaiseInput(1, Drvlut[(int)c.GetFloat("P2 Driving")], true); + } + + private static void ConvertBoosterGrip(IController c, InputState s) + { + s.ClearControllerInput(); + ConvertConsoleButtons(c, s); + ConvertDirections(c, s, 0); + ConvertDirections(c, s, 1); + + // weird mapping is intentional + s.RaiseInput(0, MachineInput.Fire, c.IsPressed("P1 Trigger")); + s.RaiseInput(0, MachineInput.Fire2, c.IsPressed("P1 Trigger 2")); + s.RaiseInput(1, MachineInput.Fire2, c.IsPressed("P1 Trigger 3")); + s.RaiseInput(1, MachineInput.Fire, c.IsPressed("P2 Trigger")); + s.RaiseInput(2, MachineInput.Fire2, c.IsPressed("P2 Trigger 2")); + s.RaiseInput(3, MachineInput.Fire2, c.IsPressed("P2 Trigger 3")); + } + + private static void ConvertProLineJoystick(IController c, InputState s) + { + s.ClearControllerInput(); + ConvertConsoleButtons7800(c, s); + ConvertDirections(c, s, 0); + ConvertDirections(c, s, 1); + s.RaiseInput(0, MachineInput.Fire, c.IsPressed("P1 Trigger")); + s.RaiseInput(0, MachineInput.Fire2, c.IsPressed("P1 Trigger 2")); + s.RaiseInput(1, MachineInput.Fire, c.IsPressed("P2 Trigger")); + s.RaiseInput(1, MachineInput.Fire2, c.IsPressed("P2 Trigger 2")); + } + + private static void ConvertLightgun(IController c, InputState s) + { + s.ClearControllerInput(); + ConvertConsoleButtons7800(c, s); + ConvertTrigger(c, s, 0); + ConvertTrigger(c, s, 1); + s.RaiseLightgunPos(0, (int)c.GetFloat("P1 VPos"), (int)c.GetFloat("P1 HPos")); + s.RaiseLightgunPos(1, (int)c.GetFloat("P2 VPos"), (int)c.GetFloat("P2 HPos")); + } + + public Action Convert { get; private set; } + + public ControllerDefinition ControlType { get; private set; } + + public A7800HawkControl(MachineBase mac) + { + var l = mac.InputState.LeftControllerJack; + var r = mac.InputState.RightControllerJack; + + foreach (var a in Adapters) + { + if (a.Left == l && a.Right == r) + { + Convert = a.Convert; + ControlType = a.Type; + return; + } + } + + throw new Exception($"Couldn't connect Atari 7800 controls \"{l}\" and \"{r}\""); + } + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/M6532.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/M6532.cs new file mode 100644 index 0000000000..58a54af72f --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/M6532.cs @@ -0,0 +1,225 @@ +using BizHawk.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + // Emulates the M6532 RIOT Chip + public class M6532 + { + private byte _ddRa = 0x00; + private byte _ddRb = 0x00; + private byte _outputA = 0x00; + + public TimerData Timer; + + public M6532() + { + + // arbitrary value to start with. + Timer.Value = 0x73; + Timer.PrescalerShift = 10; + Timer.PrescalerCount = 1 << Timer.PrescalerShift; + } + + public byte ReadMemory(ushort addr, bool peek) + { + if ((addr & 0x0200) == 0) // If not register select, read Ram + { + //return _core.Ram[(ushort)(addr & 0x007f)]; + return 0; + } + + var registerAddr = (ushort)(addr & 0x0007); + if (registerAddr == 0x00) + { + // Read Output reg A + // Combine readings from player 1 and player 2 + // actually depends on setting in SWCHCNTA (aka DDRa) + byte temp = 0;// (byte)(_core.ReadControls1(peek) & 0xF0 | ((_core.ReadControls2(peek) >> 4) & 0x0F)); + temp = (byte)(temp & ~_ddRa); + temp = (byte)(temp + (_outputA & _ddRa)); + return temp; + } + + if (registerAddr == 0x01) + { + // Read DDRA + return _ddRa; + } + + if (registerAddr == 0x02) + { + // Read Output reg B + byte temp = 0;// _core.ReadConsoleSwitches(peek); + temp = (byte)(temp & ~_ddRb); + return temp; + } + + if (registerAddr == 0x03) // Read DDRB + { + return _ddRb; + } + + if ((registerAddr & 0x5) == 0x4) + { + // Bit 0x0080 contains interrupt enable/disable + Timer.InterruptEnabled = (addr & 0x0080) != 0; + + // The interrupt flag will be reset whenever the Timer is access by a read or a write + // However, the reading of the timer at the same time the interrupt occurs will not reset the interrupt flag + // (M6532 Datasheet) + if (!(Timer.PrescalerCount == 0 && Timer.Value == 0)) + { + Timer.InterruptFlag = false; + } + + return Timer.Value; + } + + // TODO: fix this to match real behaviour + // This is an undocumented instruction whose behaviour is more dynamic then indicated here + if ((registerAddr & 0x5) == 0x5) + { + // Read interrupt flag + if (Timer.InterruptFlag) // Timer.InterruptEnabled && ) + { + return 0xC0; + } + + return 0x00; + } + + return 0x3A; + } + + public void WriteMemory(ushort addr, byte value) + { + if ((addr & 0x0200) == 0) // If the RS bit is not set, this is a ram write + { + //_core.Ram[(ushort)(addr & 0x007f)] = value; + } + else + { + // If bit 0x0010 is set, and bit 0x0004 is set, this is a timer write + if ((addr & 0x0014) == 0x0014) + { + var registerAddr = (ushort)(addr & 0x0007); + + // Bit 0x0080 contains interrupt enable/disable + Timer.InterruptEnabled = (addr & 0x0080) != 0; + + // The interrupt flag will be reset whenever the Timer is access by a read or a write + // (M6532 datasheet) + if (registerAddr == 0x04) + { + // Write to Timer/1 + Timer.PrescalerShift = 0; + Timer.Value = value; + Timer.PrescalerCount = 0; // 1 << Timer.PrescalerShift; + Timer.InterruptFlag = false; + } + else if (registerAddr == 0x05) + { + // Write to Timer/8 + Timer.PrescalerShift = 3; + Timer.Value = value; + Timer.PrescalerCount = 0; // 1 << Timer.PrescalerShift; + Timer.InterruptFlag = false; + } + else if (registerAddr == 0x06) + { + // Write to Timer/64 + Timer.PrescalerShift = 6; + Timer.Value = value; + Timer.PrescalerCount = 0; // 1 << Timer.PrescalerShift; + Timer.InterruptFlag = false; + } + else if (registerAddr == 0x07) + { + // Write to Timer/1024 + Timer.PrescalerShift = 10; + Timer.Value = value; + Timer.PrescalerCount = 0; // 1 << Timer.PrescalerShift; + Timer.InterruptFlag = false; + } + } + + // If bit 0x0004 is not set, bit 0x0010 is ignored and + // these are register writes + else if ((addr & 0x0004) == 0) + { + var registerAddr = (ushort)(addr & 0x0007); + + if (registerAddr == 0x00) + { + // Write Output reg A + _outputA = value; + } + else if (registerAddr == 0x01) + { + // Write DDRA + _ddRa = value; + } + else if (registerAddr == 0x02) + { + // Write Output reg B + // But is read only + } + else if (registerAddr == 0x03) + { + // Write DDRB + _ddRb = value; + } + } + } + } + + public void SyncState(Serializer ser) + { + ser.BeginSection("M6532"); + ser.Sync("ddra", ref _ddRa); + ser.Sync("ddrb", ref _ddRb); + ser.Sync("OutputA", ref _outputA); + Timer.SyncState(ser); + ser.EndSection(); + } + + public struct TimerData + { + public int PrescalerCount; + public byte PrescalerShift; + + public byte Value; + + public bool InterruptEnabled; + public bool InterruptFlag; + + public void Tick() + { + if (PrescalerCount == 0) + { + Value--; + PrescalerCount = 1 << PrescalerShift; + } + + PrescalerCount--; + if (PrescalerCount == 0) + { + if (Value == 0) + { + InterruptFlag = true; + PrescalerShift = 0; + } + } + } + + public void SyncState(Serializer ser) + { + ser.Sync("prescalerCount", ref PrescalerCount); + ser.Sync("prescalerShift", ref PrescalerShift); + ser.Sync("value", ref Value); + ser.Sync("interruptEnabled", ref InterruptEnabled); + ser.Sync("interruptFlag", ref InterruptFlag); + } + } + } +} \ No newline at end of file diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Maria.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Maria.cs new file mode 100644 index 0000000000..a142a32bb7 --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Maria.cs @@ -0,0 +1,50 @@ +using System; + +using BizHawk.Emulation.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + // Emulates the Atari 7800 Maria graphics chip + public class Maria : IVideoProvider + { + public int _frameHz; + + public int[] _vidbuffer; + public int[] _palette; + + public int[] GetVideoBuffer() + { + return _vidbuffer; + } + + public int VirtualWidth => 275; + public int VirtualHeight => BufferHeight; + public int BufferWidth { get; private set; } + public int BufferHeight { get; private set; } + public int BackgroundColor => unchecked((int)0xff000000); + public int VsyncNumerator => _frameHz; + public int VsyncDenominator => 1; + + // the Maria chip can directly access memory + public Func ReadMemory; + + // there are 4 maria cycles in a CPU cycle (fast access, both NTSC and PAL) + // if the 6532 or TIA are accessed (PC goes to one of those addresses) the next access will be slower by 1/2 a CPU cycle + // i.e. it will take 6 Maria cycles instead of 4 + public bool slow_access = false; + + // each frame contains 263 scanlines + // each scanline consists of 113.5 CPU cycles (fast access) which equates to 454 Maria cycles + // In total there are 29850.5 CPU cycles (fast access) in a frame + public void Execute(int cycle, int scanline) + { + + } + + public void Reset() + { + + } + + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/MemoryMap.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/MemoryMap.cs new file mode 100644 index 0000000000..64f6211966 --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/MemoryMap.cs @@ -0,0 +1,153 @@ +using System; + +using BizHawk.Common.BufferExtensions; +using BizHawk.Emulation.Common; +using BizHawk.Emulation.Cores.Components.M6502; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public partial class A7800Hawk + { + public byte ReadMemory(ushort addr) + { + if (addr < 0x0400) { + if ((addr & 0xFF) < 0x20) + { + // return TIA registers or control register if it is still unlocked + if ((A7800_control_register & 0x1) == 0 && (addr < 0x20)) + { + return 0xFF; // TODO: what to return here? + } + else + { + return TIA_regs[addr]; // TODO: what to return here? + } + } + else if ((addr & 0xFF) < 0x40) + { + if ((A7800_control_register & 0x2) > 0) + { + return Maria_regs[(addr & 0x3F) - 0x20]; + } + else + { + return 0xFF; + } + } + else if (addr < 0x100) + { + // RAM block 0 + return RAM[addr - 0x40 + 0x840]; + } + else if (addr < 0x200) + { + // RAM block 1 + return RAM[addr - 0x140 + 0x940]; + } + else if (addr < 0x300) + { + return regs_6532[addr - 0x240]; + } + else + { + return 0xFF; // what is mapped here? + } + } + else if (addr < 0x480) + { + return 0xFF; // cartridge space available + } + else if (addr < 0x500) + { + // this is where RAM for the 6532 resides for use in 2600 mode + return 0xFF; + } + else if (addr < 0x1800) + { + return 0xFF; // cartridge space available + } + else if (addr < 0x2800) + { + return RAM[addr - 0x1800]; + } + else if (addr < 0x4000) + { + return RAM[addr - 0x2800 + 0x800]; + } + else + { + return 0xFF; // cartridge and other OPSYS + } + } + + public void WriteMemory(ushort addr, byte value) + { + if (addr < 0x0400) + { + if ((addr & 0xFF) < 0x20) + { + // return TIA registers or control register if it is still unlocked + if ((A7800_control_register & 0x1) == 0 && (addr < 0x20)) + { + A7800_control_register = value; // TODO: what to return here? + } + else + { + TIA_regs[addr] = value; // TODO: what to return here? + } + } + else if ((addr & 0xFF) < 0x40) + { + if ((A7800_control_register & 0x2) > 0) + { + Maria_regs[(addr & 0x3F) - 0x20] = value; + } + } + else if (addr < 0x100) + { + // RAM block 0 + RAM[addr - 0x40 + 0x840] = value; + } + else if (addr < 0x200) + { + // RAM block 1 + RAM[addr - 0x140 + 0x940] = value; + } + else if (addr < 0x300) + { + regs_6532[addr - 0x240] = value; + } + else + { + // what is mapped here? + } + } + else if (addr < 0x480) + { + // cartridge space available + } + else if (addr < 0x500) + { + // this is where RAM for the 6532 resides for use in 2600 mode + // is it accessible in 7800 mode? + } + else if (addr < 0x1800) + { + // cartridge space available + } + else if (addr < 0x2800) + { + RAM[addr - 0x1800] = value; + } + else if (addr < 0x4000) + { + RAM[addr - 0x2800 + 0x800] = value; + } + else + { + // cartridge and other OPSYS + } + } + + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Readme.txt b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Readme.txt new file mode 100644 index 0000000000..84fa199c5f --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/Readme.txt @@ -0,0 +1 @@ +todo: diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/TIA.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/TIA.cs new file mode 100644 index 0000000000..4c6ef5f20d --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/TIA.cs @@ -0,0 +1,334 @@ +using System; +using System.Numerics; + +using BizHawk.Emulation.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + // Emulates the TIA + public partial class TIA : ISoundProvider + { + public byte BusState; + + private bool _doTicks; + + private byte _hsyncCnt; + private int _capChargeStart; + private bool _capCharging; + public int AudioClocks; // not savestated + + private readonly Audio[] AUD = { new Audio(), new Audio() }; + + // current audio register state used to sample correct positions in the scanline (clrclk 0 and 114) + ////public byte[] current_audio_register = new byte[6]; + public readonly short[] LocalAudioCycles = new short[2000]; + + public void Reset() + { + _hsyncCnt = 0; + _capChargeStart = 0; + _capCharging = false; + AudioClocks = 0; + + _doTicks = false; + } + + // Execute TIA cycles + public void Execute(int cycles) + { + // do the audio sampling + if (_hsyncCnt == 36 || _hsyncCnt == 148) + { + LocalAudioCycles[AudioClocks] += (short)(AUD[0].Cycle() / 2); + LocalAudioCycles[AudioClocks] += (short)(AUD[1].Cycle() / 2); + AudioClocks++; + } + + } + + public byte ReadMemory(ushort addr, bool peek) + { + var maskedAddr = (ushort)(addr & 0x000F); + byte coll = 0; + int mask = 0; + + if (maskedAddr == 0x00) // CXM0P + { + + } + + if (maskedAddr == 0x01) // CXM1P + { + + } + + if (maskedAddr == 0x02) // CXP0FB + { + + } + + if (maskedAddr == 0x03) // CXP1FB + { + + } + + if (maskedAddr == 0x04) // CXM0FB + { + + } + + if (maskedAddr == 0x05) // CXM1FB + { + + } + + if (maskedAddr == 0x06) // CXBLPF + { + + } + + if (maskedAddr == 0x07) // CXPPMM + { + + } + + // inputs 0-3 are measured by a charging capacitor, these inputs are used with the paddles and the keyboard + // Changing the hard coded value will change the paddle position. The range seems to be roughly 0-56000 according to values from stella + // 6105 roughly centers the paddle in Breakout + if (maskedAddr == 0x08) // INPT0 + { + + } + + if (maskedAddr == 0x09) // INPT1 + { + + } + + if (maskedAddr == 0x0A) // INPT2 + { + + } + + if (maskedAddr == 0x0B) // INPT3 + { + + } + + if (maskedAddr == 0x0C) // INPT4 + { + + } + + if (maskedAddr == 0x0D) // INPT5 + { + + } + + // some bits of the databus will be undriven when a read call is made. Our goal here is to sort out what + // happens to the undriven pins. Most of the time, they will be in whatever state they were when previously + // assigned in some other bus access, so let's go with that. + coll += (byte)(mask & BusState); + + if (!peek) + { + BusState = coll; + } + + return coll; + } + + public void WriteMemory(ushort addr, byte value, bool poke) + { + var maskedAddr = (ushort)(addr & 0x3f); + if (!poke) + { + BusState = value; + } + + if (maskedAddr == 0x00) // VSYNC + { + + } + else if (maskedAddr == 0x01) // VBLANK + { + + } + else if (maskedAddr == 0x02) // WSYNC + { + + } + else if (maskedAddr == 0x04) // NUSIZ0 + { + + } + else if (maskedAddr == 0x05) // NUSIZ1 + { + + } + else if (maskedAddr == 0x06) // COLUP0 + { + + } + else if (maskedAddr == 0x07) // COLUP1 + { + + } + else if (maskedAddr == 0x08) // COLUPF + { + + } + else if (maskedAddr == 0x09) // COLUBK + { + + } + else if (maskedAddr == 0x0A) // CTRLPF + { + + } + else if (maskedAddr == 0x0B) // REFP0 + { + + } + else if (maskedAddr == 0x0C) // REFP1 + { + + } + else if (maskedAddr == 0x0D) // PF0 + { + + } + else if (maskedAddr == 0x0E) // PF1 + { + + } + else if (maskedAddr == 0x0F) // PF2 + { + + } + else if (maskedAddr == 0x10) // RESP0 + { + + } + else if (maskedAddr == 0x11) // RESP1 + { + + } + else if (maskedAddr == 0x12) // RESM0 + { + + } + else if (maskedAddr == 0x13) // RESM1 + { + + } + else if (maskedAddr == 0x14) // RESBL + { + + } + else if (maskedAddr == 0x15) // AUDC0 + { + AUD[0].AUDC = (byte)(value & 15); + } + else if (maskedAddr == 0x16) // AUDC1 + { + AUD[1].AUDC = (byte)(value & 15); + } + else if (maskedAddr == 0x17) // AUDF0 + { + AUD[0].AUDF = (byte)((value & 31) + 1); + } + else if (maskedAddr == 0x18) // AUDF1 + { + AUD[1].AUDF = (byte)((value & 31) + 1); + } + else if (maskedAddr == 0x19) // AUDV0 + { + AUD[0].AUDV = (byte)(value & 15); + } + else if (maskedAddr == 0x1A) // AUDV1 + { + AUD[1].AUDV = (byte)(value & 15); + } + else if (maskedAddr == 0x1B) // GRP0 + { + + } + else if (maskedAddr == 0x1C) // GRP1 + { + + } + else if (maskedAddr == 0x1D) // ENAM0 + { + + } + else if (maskedAddr == 0x1E) // ENAM1 + { + + } + else if (maskedAddr == 0x1F) // ENABL + { + + } + else if (maskedAddr == 0x20) // HMP0 + { + + } + else if (maskedAddr == 0x21) // HMP1 + { + + } + else if (maskedAddr == 0x22) // HMM0 + { + + } + else if (maskedAddr == 0x23) // HMM1 + { + + } + else if (maskedAddr == 0x24) // HMBL + { + + } + else if (maskedAddr == 0x25) // VDELP0 + { + + } + else if (maskedAddr == 0x26) // VDELP1 + { + + } + else if (maskedAddr == 0x27) // VDELBL + { + + } + else if (maskedAddr == 0x28) // RESMP0 + { + + } + else if (maskedAddr == 0x29) // RESMP1 + { + + } + else if (maskedAddr == 0x2A) // HMOVE + { + + } + else if (maskedAddr == 0x2B) // HMCLR + { + + } + else if (maskedAddr == 0x2C) // CXCLR + { + + } + } + + private enum AudioRegister : byte + { + AUDC, AUDF, AUDV + } + + private int _frameStartCycles, _frameEndCycles; + } +} \ No newline at end of file diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.Audio.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.Audio.cs new file mode 100644 index 0000000000..cf5aa3e0c7 --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.Audio.cs @@ -0,0 +1,212 @@ +using System; +using BizHawk.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public partial class TIA + { + public class Audio + { + // noise/division control + public byte AUDC = 0; + + // frequency divider + public byte AUDF = 1; + + // volume + public byte AUDV = 0; + + // 2 state counter + private bool sr1 = true; + + // 4 bit shift register + private int sr4 = 0x0f; + + // 5 bit shift register + private int sr5 = 0x1f; + + // 9 bit shift register + private int sr9 = 0x1ff; + + // 3 state counter + private int sr3 = 2; + + // counter based off AUDF + private byte freqcnt; + + // latched audio value + private bool on = true; + + private bool Run3() + { + sr3++; + if (sr3 == 3) + { + sr3 = 0; + return true; + } + + return false; + } + + private bool Run4() + { + bool ret = (sr4 & 1) != 0; + bool c = ((sr4 & 1) != 0) ^ ((sr4 & 2) != 0); + sr4 = (sr4 >> 1) | (c ? 8 : 0); + return ret; + } + + private bool Run5() + { + bool ret = (sr5 & 1) != 0; + bool c = ((sr5 & 1) != 0) ^ ((sr5 & 4) != 0); + sr5 = (sr5 >> 1) | (c ? 16 : 0); + return ret; + } + + private bool One4() + { + bool ret = (sr4 & 1) != 0; + sr4 = (sr4 >> 1) | 8; + return ret; + } + + private bool One5() + { + bool ret = (sr5 & 1) != 0; + sr5 = (sr5 >> 1) | 16; + return ret; + } + + private bool Run1() + { + sr1 = !sr1; + return !sr1; + } + + private bool Run9() + { + bool ret = (sr9 & 1) != 0; + bool c = ((sr9 & 1) != 0) ^ ((sr9 & 16) != 0); + sr9 = (sr9 >> 1) | (c ? 256 : 0); + return ret; + } + + /// + /// call me approx 31k times a second + /// + /// 16 bit audio sample + public short Cycle() + { + if (++freqcnt >= AUDF) + { + freqcnt = 0; + switch (AUDC) + { + case 0x00: + case 0x0b: + // Both have a 1 s + One5(); + on = One4(); + break; + + case 0x01: + // Both run, but the 5 bit is ignored + on = Run4(); + //Run5(); + break; + case 0x02: + if ((sr5 & 0x0f) == 0 || (sr5 & 0x0f) == 0x0f) + { + on = Run4(); + } + + Run5(); + break; + case 0x03: + if (Run5()) + { + on = Run4(); + } + + break; + + case 0x04: + Run5(); + One4(); + on = Run1(); + break; + + case 0x05: + One5(); + Run4(); + on = Run1(); + break; + + case 0x06: + case 0x0a: + Run5(); + if ((sr5 & 0x0f) == 0) + { + on = false; + } + else if ((sr5 & 0x0f) == 0x0f) + { + on = true; + } + + break; + + case 0x07: + case 0x09: + on = Run5(); + break; + + case 0x08: + on = Run9(); + break; + case 0x0c: + case 0x0d: + if (Run3()) + { + on = Run1(); + } + + break; + case 0x0e: + if (Run3()) + { + goto case 0x06; + } + + break; + case 0x0f: + if (Run3()) + { + goto case 0x07; + } + + break; + } + } + + return (short)(on ? AUDV * 1092 : 0); + } + + public void SyncState(Serializer ser) + { + ser.Sync("AUDC", ref AUDC); + ser.Sync("AUDF", ref AUDF); + ser.Sync("AUDV", ref AUDV); + ser.Sync("sr1", ref sr1); + ser.Sync("sr3", ref sr3); + ser.Sync("sr4", ref sr4); + ser.Sync("sr5", ref sr5); + ser.Sync("sr9", ref sr9); + ser.Sync("freqcnt", ref freqcnt); + ser.Sync("on", ref on); + } + } + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.ISoundProvider.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.ISoundProvider.cs new file mode 100644 index 0000000000..3a85b7bbd0 --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.ISoundProvider.cs @@ -0,0 +1,65 @@ +using System; +using BizHawk.Emulation.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public partial class TIA : ISoundProvider + { + public bool CanProvideAsync => false; + + public void SetSyncMode(SyncSoundMode mode) + { + if (mode != SyncSoundMode.Sync) + { + throw new InvalidOperationException("Only Sync mode is supported."); + } + } + + public SyncSoundMode SyncMode => SyncSoundMode.Sync; + + public void GetSamplesSync(out short[] samples, out int nsamp) + { + short[] ret = new short[_spf * 2]; + GetSamples(ret); + samples = ret; + nsamp = _spf; + } + + public void GetSamplesAsync(short[] samples) + { + throw new NotSupportedException("Async is not available"); + } + + public void DiscardSamples() + { + AudioClocks = 0; + } + + private readonly int _spf; + + // Exposing this as GetSamplesAsync would allow this to provide async sound + // However, it does nothing special for async sound so I don't see a point + private void GetSamples(short[] samples) + { + if (AudioClocks > 0) + { + var samples31Khz = new short[AudioClocks]; // mono + + for (int i = 0; i < AudioClocks; i++) + { + samples31Khz[i] = LocalAudioCycles[i]; + LocalAudioCycles[i] = 0; + } + + // convert from 31khz to 44khz + for (var i = 0; i < samples.Length / 2; i++) + { + samples[i * 2] = samples31Khz[(int)(((double)samples31Khz.Length / (double)(samples.Length / 2)) * i)]; + samples[(i * 2) + 1] = samples[i * 2]; + } + } + + AudioClocks = 0; + } + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.SyncState.cs b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.SyncState.cs new file mode 100644 index 0000000000..100bdf5361 --- /dev/null +++ b/BizHawk.Emulation.Cores/Consoles/Atari/A7800Hawk/TIA_Sound/Tia.SyncState.cs @@ -0,0 +1,28 @@ +using BizHawk.Common; + +namespace BizHawk.Emulation.Cores.Atari.A7800Hawk +{ + public partial class TIA + { + public void SyncState(Serializer ser) + { + ser.BeginSection("TIA"); + + ser.Sync("hsyncCnt", ref _hsyncCnt); + + // add everything to the state + ser.Sync("Bus_State", ref BusState); + + ser.Sync("Ticks", ref _doTicks); + + // some of these things weren't in the state because they weren't needed if + // states were always taken at frame boundaries + ser.Sync("capChargeStart", ref _capChargeStart); + ser.Sync("capCharging", ref _capCharging); + ser.Sync("AudioClocks", ref AudioClocks); + ser.Sync("FrameStartCycles", ref _frameStartCycles); + ser.Sync("FrameEndCycles", ref _frameEndCycles); + + } + } +} diff --git a/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/BxROM.cs b/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/BxROM.cs index 7a3ee3373c..b333587a0d 100644 --- a/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/BxROM.cs +++ b/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/BxROM.cs @@ -7,14 +7,17 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES { //configuration int prg_bank_mask_32k; + int chr_bank_mask_8k; //state int prg_bank_32k; + int chr_bank_8k; public override void SyncState(Serializer ser) { base.SyncState(ser); ser.Sync("prg_bank_32k", ref prg_bank_32k); + ser.Sync("chr_bank_8k", ref chr_bank_8k); } public override bool Configure(NES.EDetectionOrigin origin) @@ -24,7 +27,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES case "AVE-NINA-07": // wally bear and the gang // it's not the NINA_001 but something entirely different; actually a colordreams with VRAM // this actually works - AssertPrg(128); AssertChr(0); AssertWram(0); AssertVram(8); + AssertPrg(32,128); AssertChr(0,16); AssertWram(0); AssertVram(0,8); break; case "IREM-BNROM": //Mashou (J).nes @@ -37,6 +40,7 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES } prg_bank_mask_32k = Cart.prg_size / 32 - 1; + chr_bank_mask_8k = Cart.chr_size / 8 - 1; SetMirrorType(Cart.pad_h, Cart.pad_v); @@ -53,6 +57,26 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES { value = HandleNormalPRGConflict(addr, value); prg_bank_32k = value & prg_bank_mask_32k; + chr_bank_8k = ((value >> 4) & 0xF) & chr_bank_mask_8k; + } + + public override byte ReadPPU(int addr) + { + if (addr<0x2000) + { + if (VRAM != null) + { + return VRAM[addr | (chr_bank_8k << 13)]; + } + else + { + return VROM[addr | (chr_bank_8k << 13)]; + } + } + else + { + return base.ReadPPU(addr); + } } } diff --git a/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/MMC3.cs b/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/MMC3.cs index f0dcabb7e7..999d23605b 100644 --- a/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/MMC3.cs +++ b/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/MMC3.cs @@ -418,19 +418,5 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES mmc3 = new MMC3(this, num_prg_banks); SetMirrorType(EMirrorType.Vertical); } - - //used by a couple of boards for controlling nametable wiring with the mapper - protected int RewireNametable_TLSROM(int addr, int bitsel) - { - int bank_1k = mmc3.Get_CHRBank_1K(addr & 0x1FFF); - int nt = (bank_1k >> bitsel) & 1; - int ofs = addr & 0x3FF; - addr = 0x2000 + (nt << 10); - addr |= (ofs); - return addr; - } - } - - } diff --git a/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/TLSROM.cs b/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/TLSROM.cs index ffea03e63c..0fe238bfeb 100644 --- a/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/TLSROM.cs +++ b/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/TLSROM.cs @@ -1,9 +1,15 @@ +using System; +using BizHawk.Common; +using BizHawk.Common.NumberExtensions; + namespace BizHawk.Emulation.Cores.Nintendo.NES { //aka mapper 118 //wires the mapper outputs to control the nametables public sealed class TLSROM : MMC3Board_Base { + public int[] nametables = new int[4]; + public override bool Configure(NES.EDetectionOrigin origin) { //analyze board type @@ -20,8 +26,8 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES AssertBattery(true); break; case "TENGEN-800037": //Alien Syndrome (U) - // this board is actually a RAMBO-1 (mapper064) with TLS-style rewiring - // but it seems to work fine here, so lets not worry about it + // this board is actually a RAMBO-1 (mapper064) with TLS-style rewiring + // but it seems to work fine here, so lets not worry about it AssertPrg(128); AssertChr(128); AssertVram(0); AssertWram(0); break; case "MAPPER158": @@ -38,24 +44,86 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES BaseSetup(); SetMirrorType(EMirrorType.Vertical); + //maybe need other initialization + nametables[0] = 0; + nametables[1] = 1; + nametables[2] = 0; + nametables[3] = 1; + return true; } public override void WritePRG(int addr, byte value) { - base.WritePRG(addr, value); + int nt = value >> 7; + + if ((addr & 0x6001) == 0x1) + { + if (!mmc3.chr_mode) + { + switch (mmc3.reg_addr) + { + case 0: + nametables[0] = nt; + nametables[1] = nt; + break; + case 1: + nametables[2] = nt; + nametables[3] = nt; + break; + } + } + else + { + switch (mmc3.reg_addr) + { + case 2: + nametables[0] = nt; + break; + case 3: + nametables[1] = nt; + break; + case 4: + nametables[2] = nt; + break; + case 5: + nametables[3] = nt; + break; + } + } + } + + if ((addr & 0x6001) != 0x2000) + base.WritePRG(addr, value); } public override byte ReadPPU(int addr) { if (addr < 0x2000) return base.ReadPPU(addr); - else return base.ReadPPU(RewireNametable_TLSROM(addr, 7)); + else + { + int nt = ((addr - 0x2000) >> 10) & 0x3; + addr = 0x2000 + (addr & 0x3FF) + (nametables[nt] << 10); + return base.ReadPPU(addr); + + } } public override void WritePPU(int addr, byte value) { if (addr < 0x2000) base.WritePPU(addr, value); - else base.WritePPU(RewireNametable_TLSROM(addr, 7), value); + else + { + int nt = ((addr - 0x2000) >> 10) & 0x3; + addr = 0x2000 + (addr & 0x3FF) + (nametables[nt] << 10); + base.WritePPU(addr, value); + } + } + public override void SyncState(Serializer ser) + { + base.SyncState(ser); + ser.Sync("nametables", ref nametables, false); + } } } \ No newline at end of file diff --git a/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMCFK23C.cs b/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMCFK23C.cs index 3f70692c66..61ec883370 100644 --- a/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMCFK23C.cs +++ b/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/UNIF/UNIF_BMCFK23C.cs @@ -9,8 +9,12 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES private IntBuffer chr_regs_1k = new IntBuffer(8); public IntBuffer prg_regs_8k = new IntBuffer(4); - private bool dip_switch; - private byte dip_switch_setting; + [MapperProp] + public bool dip_switch; + + [MapperProp] + public byte dip_switch_setting; + private int unromChr; private int prg_mask_8k, chr_mask_1k; @@ -29,10 +33,10 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES return false; } - exRegs[0] = 0;//xFF; - exRegs[1] = 0;// xFF; - exRegs[2] = 0;// xFF; - exRegs[3] = 0;// x FF; + exRegs[0] = 0; // xFF; + exRegs[1] = 0; // xFF; + exRegs[2] = 0; // xFF; + exRegs[3] = 0; // x FF; exRegs[4] = 0xFF; exRegs[5] = 0xFF; exRegs[6] = 0xFF; @@ -83,6 +87,8 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES ser.Sync("prg_regs_8k", ref prg_regs_8k); ser.Sync("prg_mask", ref prg_mask_8k); ser.Sync("chr_mask", ref chr_mask_1k); + ser.Sync("dip_switch", ref dip_switch); + ser.Sync("dip_switch_setting", ref dip_switch_setting); } void UpdateChr() diff --git a/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NESControllers.cs b/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NESControllers.cs index 765eadc234..48adc81990 100644 --- a/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NESControllers.cs +++ b/BizHawk.Emulation.Cores/Consoles/Nintendo/NES/NESControllers.cs @@ -933,12 +933,12 @@ namespace BizHawk.Emulation.Cores.Nintendo.NES return 0; int idx = row * 8 + column * 4; - byte ret = 0; + byte ret = 0x1E; - if (c.IsPressed(Buttons[idx])) ret |= 16; - if (c.IsPressed(Buttons[idx + 1])) ret |= 8; - if (c.IsPressed(Buttons[idx + 2])) ret |= 4; - if (c.IsPressed(Buttons[idx + 3])) ret |= 2; + if (c.IsPressed(Buttons[idx])) ret &= 0x0E; + if (c.IsPressed(Buttons[idx + 1])) ret &= 0x16; + if (c.IsPressed(Buttons[idx + 2])) ret &= 0x1A; + if (c.IsPressed(Buttons[idx + 3])) ret &= 0x1C; // nothing is clocked here return ret; diff --git a/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IStatable.cs b/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IStatable.cs index c5ce9019c7..c90de87d53 100644 --- a/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IStatable.cs +++ b/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.IStatable.cs @@ -68,10 +68,6 @@ namespace BizHawk.Emulation.Cores.Nintendo.SNES _controller = tmp; ssc.Serialize(bw); } - else // hack: dummy controller info - { - bw.Write(reader.ReadBytes(536)); - } bw.Close(); _savestatebuff = ms.ToArray(); diff --git a/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.cs b/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.cs index 8317a98755..ad63299a0e 100644 --- a/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.cs +++ b/BizHawk.Emulation.Cores/Consoles/Nintendo/SNES/LibsnesCore.cs @@ -38,7 +38,6 @@ namespace BizHawk.Emulation.Cores.Nintendo.SNES Header = "65816: PC, mnemonic, operands, registers (A, X, Y, S, D, DB, flags (NVMXDIZC), V, H)" }; - ser.Register(_tracer); ser.Register(new W65816_DisassemblerService()); _game = game; @@ -180,6 +179,11 @@ namespace BizHawk.Emulation.Cores.Nintendo.SNES bw.Close(); _savestatebuff = ms.ToArray(); } + + if (CurrentProfile == "Compatibility") + { + ser.Register(_tracer); + } } private readonly GameInfo _game; diff --git a/BizHawk.sln.DotSettings b/BizHawk.sln.DotSettings index 57136fc367..f660132933 100644 --- a/BizHawk.sln.DotSettings +++ b/BizHawk.sln.DotSettings @@ -76,6 +76,7 @@ PC PCE PCECD + PPU PSP PSX RAM @@ -83,10 +84,12 @@ SG SGB SGX + SHA SNES TAS TI TIA + UI VBA ROM <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /> diff --git a/output/dll/MusashiDLL.dll b/output/dll/MusashiDLL.dll deleted file mode 100644 index 218ed70f0b..0000000000 Binary files a/output/dll/MusashiDLL.dll and /dev/null differ diff --git a/output/dll/octoshock.dll b/output/dll/octoshock.dll index 2a14816faf..a283e0fef8 100644 Binary files a/output/dll/octoshock.dll and b/output/dll/octoshock.dll differ diff --git a/psx/octoshock/psx/psx.cpp b/psx/octoshock/psx/psx.cpp index d94c7cab54..ba358a647b 100644 --- a/psx/octoshock/psx/psx.cpp +++ b/psx/octoshock/psx/psx.cpp @@ -60,6 +60,15 @@ static bool PrevInterlaced; static Deinterlacer deint; static EmulateSpecStruct espec; +template inline void reconstruct(T* t) { + t->~T(); + new(t) T(); +} +template inline void reconstruct(T* t, A a) { + t->~T(); + new(t) T(a); +} + namespace MDFN_IEN_PSX { @@ -1082,11 +1091,12 @@ struct { void Initialize() { - for(int i=0;i<2;i++) + for(int i=0;i<10;i++) { ports[i].type = ePeripheralType_None; memset(ports[i].buffer,0,sizeof(ports[i].buffer)); } + reconstruct(FIO); } //TODO: "Take care to call ->Power() only if the device actually changed."