-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruncommand_win
More file actions
598 lines (515 loc) · 16.2 KB
/
runcommand_win
File metadata and controls
598 lines (515 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
#! /usr/bin/ruby -E:UTF-8
# -*- mode:Ruby; tab-width:4; coding:UTF-8; -*-
# vi:set ft=ruby ts=4 fenc=UTF-8 :
#----------------------------------------------------------------
# runcommand_win
#
# 2020/09/18 opa🙂
#----------------------------------------------------------------
ProgName = "runcommand_win"
Version = "1.06"
#=====dpk===== Copyright2020
Copyright = "Copyright (c) 2020-2024 by opa"
#=====dpk=====
require 'pathname'
require 'tempfile'
require 'logger'
require 'rexml/document'
require 'fileutils'
RETROPIE_CONFIG = File.expand_path("~/RetroPie-Config")
CONFIG_DIR = File.join(RETROPIE_CONFIG, "configs")
RETROARCH_EXE_NAME = "retroarch.exe"
#=====dpk===== os_is_windows?
# Windows環境下かどうか判定する
module Kernel
module_function
if RUBY_PLATFORM =~ /mswin(?!ce)|mingw|cygwin|bccwin|emx/i
def os_is_windows?; true; end
else
def os_is_windows?; false; end
end
end
#=====dpk=====
# from_dirからの相対パスを得る(相対パスで表せなければ元のまま)
def relpath(path, from_dir)
return Pathname(path).relative_path_from(Pathname(from_dir)).to_s
end
# パス区切り文字を / に統一する(→SEPARATOR)
def treat_path_separator(path)
path = path.gsub(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
return path
end
# パス区切り文字を \ に統一する(→ALT_SEPARATOR)
def treat_path_alt_separator(path)
path = path.gsub(File::SEPARATOR, File::ALT_SEPARATOR) if File::ALT_SEPARATOR
return path
end
# Win32(WIDE)との橋渡し用
module Win32
WIDE = Encoding::UTF_16LE
WIDE_NUL = "\0".encode(WIDE).freeze
WIDE_SIZE = WIDE_NUL.bytesize
def self.wstr(size); WIDE_NUL * size; end
def self.to_wstr!(s); s ? s.encode!(WIDE).concat(WIDE_NUL) : nil; end
def self.to_wstr(s); s ? s.encode(WIDE).concat(WIDE_NUL) : nil; end
def self.from_wstr(s)
if s.is_a?(String)
s = s.dup.force_encoding(WIDE) if s.encoding != WIDE
return (i = s.index(WIDE_NUL)) ? s[0,i].encode! : s.encode
else
s = DL::CPtr.new(s) if s.is_a?(Integer)
return nil if s.null?
i = 0; i += 2 until s[i] == 0 && s[i+1] == 0 # WIDE_SIZE==2に依存
return s.to_s(i).force_encoding(WIDE).encode!
end
end
end
# Ruby 2.0以降はFiddleを使う、Win32APIのようなもの
if os_is_windows?
require 'fiddle/import'
class Win32::API
DLL = {}
def typemap(t)
case t
when "V"; Fiddle::TYPE_VOID
when /^[PH]$/; Fiddle::TYPE_VOIDP
when /^[NLI]$/; Fiddle::TYPE_LONG
when "Q"; Fiddle::TYPE_LONG_LONG
else; fail
end
end
private :typemap
def initialize(dllname, func, import, export = nil, calltype = :stdcall)
@import = [import].join.each_char.map { |v| typemap(v) }
handle = DLL[dllname] ||= Fiddle.dlopen(dllname)
@func = Fiddle::Function.new(handle[func], @import, typemap(export),
Fiddle::Importer.const_get(:CALL_TYPE_TO_ABI)[calltype])
rescue Fiddle::DLError => e
raise LoadError, e.message, e.backtrace
end
def call(*args)
args.each_with_index do |x, i|
case @import[i]
when Fiddle::TYPE_VOIDP
args[i], = ((x.nil? || x.is_a?(String)) ? [x].pack("p") : [x.to_i].pack("J")).unpack("j")
when Fiddle::TYPE_LONG
args[i], = [x].pack("L").unpack("l")
when Fiddle::TYPE_LONG_LONG
args[i], = [x].pack("Q").unpack("q")
else
fail
end
end
ret, = @func.call(*args)
return ret || 0
end
end
module Win32
if Fiddle::SIZEOF_VOIDP == Fiddle::SIZEOF_LONG_LONG
PROCESSOR_ARCHITECTURE = :AMD64
else
PROCESSOR_ARCHITECTURE = :x86
end
end
else
class Win32::API; end
end
class Win32::API
FALSE = 0
TRUE = 1
# Win64では、ポインタとハンドルは64bit
class Struct
AMD64 = (Win32::PROCESSOR_ARCHITECTURE == :AMD64)
STARTUPINFO = AMD64 ? "Lx4p3L8S2x4PQ3" : "Lp3L8S2PL3"
PROCESS_INFORMATION = AMD64 ? "Q2L2" : "L4"
PROCESSENTRY32 = AMD64 ? "L3x4PL3lLa*" : "L3PL3lLa*"
MSG = AMD64 ? "QLx4Q2L4" : "L8"
WNDCLASS = AMD64 ? "Lx4Ql2Q4p2" : "L2l2L4p2"
end
def self.CloseHandle(hObject)
@@CloseHandle ||= new("kernel32", "CloseHandle", "H", "I")
r = @@CloseHandle.call(hObject)
fail ArgumentError.new("CloseHandle") if r == 0
end
SW_HIDE = 0
SW_SHOWNORMAL = 1
CREATE_BREAKAWAY_FROM_JOB = 0x01000000
CREATE_DEFAULT_ERROR_MODE = 0x04000000
CREATE_NEW_CONSOLE = 0x00000010
CREATE_NEW_PROCESS_GROUP = 0x00000200
CREATE_NO_WINDOW = 0x08000000
CREATE_PROTECTED_PROCESS = 0x00040000
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000
CREATE_SECURE_PROCESS = 0x00400000
CREATE_SEPARATE_WOW_VDM = 0x00000800
CREATE_SHARED_WOW_VDM = 0x00001000
CREATE_SUSPENDED = 0x00000004
CREATE_UNICODE_ENVIRONMENT = 0x00000400
DEBUG_ONLY_THIS_PROCESS = 0x00000002
DEBUG_PROCESS = 0x00000001
DETACHED_PROCESS = 0x00000008
EXTENDED_STARTUPINFO_PRESENT = 0x00080000
INHERIT_PARENT_AFFINITY = 0x00010000
STARTF_USESHOWWINDOW = 0x00000001
def self.CreateProcess(lpCommandLine, dwCreationFlags:0, wShowWindow:nil)
@@CreateProcess ||= new("kernel32", "CreateProcessW", "PPPPIIPPPP", "I")
si = [0, nil, nil ,nil, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, nil, 0, 0, 0]
if wShowWindow
si[11] |= STARTF_USESHOWWINDOW
si[12] = wShowWindow
end
si[0] = si.pack(Struct::STARTUPINFO).bytesize
si = si.pack(Struct::STARTUPINFO)
pi = [0, 0, 0, 0].pack(Struct::PROCESS_INFORMATION)
r = @@CreateProcess.call(nil, Win32::to_wstr(lpCommandLine), nil, nil, 0, dwCreationFlags, nil, nil, si, pi)
fail ArgumentError.new("CreateProcess") if r == 0
pi = pi.unpack(Struct::PROCESS_INFORMATION)
pi = { hProcess:pi[0], hThread:pi[1], dwProcessId:pi[2], dwThreadId:pi[3] }
if block_given?
begin
hProcess = pi[:hProcess]
hThread = pi[:hThread]
return yield(pi)
ensure
CloseHandle(hThread)
CloseHandle(hProcess)
end
else
return pi
end
end
TH32CS_SNAPPROCESS = 0x00000002
def self.CreateToolhelp32Snapshot(dwFlags, th32ProcessID = 0)
@@CreateToolhelp32Snapshot ||= new("kernel32", "CreateToolhelp32Snapshot", "II", "H")
hSnapshot = @@CreateToolhelp32Snapshot.call(dwFlags, th32ProcessID)
if block_given?
begin
return yield(hSnapshot)
ensure
CloseHandle(hSnapshot)
end
else
return hSnapshot
end
end
MAX_PATH = 260
def self.Process32Next(hSnapshot)
@@Process32Next ||= new("kernel32", "Process32NextW", "HP", "I")
pe = [0, 0, 0, nil, 0, 0, 0, 0, 0, Win32::wstr(MAX_PATH+2)]
pe[0] = pe.pack(Struct::PROCESSENTRY32).bytesize
pe = pe.pack(Struct::PROCESSENTRY32)
r = @@Process32Next.call(hSnapshot, pe)
return nil if r == 0
pe = pe.unpack(Struct::PROCESSENTRY32)
return {
# cntUsage: pe[1],
th32ProcessID: pe[2],
# th32DefaultHeapID: pe[3],
# th32ModuleID: pe[4],
cntThreads: pe[5],
th32ParentProcessID: pe[6],
pcPriClassBase: pe[7],
# dwFlags: pe[8],
szExeFile: Win32::from_wstr(pe[9]),
}
end
end
# 子孫が死に絶えるまで待つsystem()
def system_wait_descendant(lpCommandLine, dwCreationFlags:0, wShowWindow:nil)
Win32::API.CreateProcess(lpCommandLine, dwCreationFlags:dwCreationFlags, wShowWindow:wShowWindow) do |pi|
descendants = { pi[:dwProcessId] => true }
sleep_pediod = 0.025
while !descendants.empty?
descendants.each_key { |pid| descendants[pid] = false }
Win32::API.CreateToolhelp32Snapshot(Win32::API::TH32CS_SNAPPROCESS) do |snapshot|
while (pe = Win32::API.Process32Next(snapshot))
sn_pid = pe[:th32ProcessID]
sn_ppid = pe[:th32ParentProcessID]
descendants[sn_pid] = true if descendants.has_key?(sn_pid)
descendants[sn_pid] = true if descendants.has_key?(sn_ppid)
end
end
descendants.delete_if { |pid, live| !live }
yield(pi, descendants.keys) if block_given?
sleep(sleep_pediod)
sleep_pediod += 0.025 if sleep_pediod < 0.5
end
end
end
# cmd.exe向けシェルエスケープ(簡易)
def Win32_cmdshell_escape(*cmd)
return cmd.map{ |t|
case t
when ""
'""'
when /[\s'"{}]/
%|"#{t.gsub('"', '""')}"|
else
t
end
}.join(" ")
end
# system_wait_descendantでコマンド実行
def win32_system_fg(*cmd)
cmd = Win32_cmdshell_escape(*cmd)
$log.info { "Exec: #{cmd}" }
system_wait_descendant(cmd)
end
# system_wait_descendantでコマンド実行(コンソール非表示)
def win32_system_bg(*cmd)
cmd = Win32_cmdshell_escape(*cmd)
$log.info { "Exec: #{cmd}" }
system_wait_descendant(cmd, wShowWindow:Win32::API::SW_HIDE)
end
def get_retroarch_home
if ENV["APPDATA"]
dir = File.absolute_path("RetroArch", ENV["APPDATA"])
if File.directory?(dir) && File.executable?(File.join(dir, RETROARCH_EXE_NAME))
return dir
end
end
if ENV["ChocolateyToolsLocation"]
dir = File.absolute_path("RetroArch-Win64", ENV["ChocolateyToolsLocation"])
if File.directory?(dir) && File.executable?(File.join(dir, RETROARCH_EXE_NAME))
return dir
end
end
if ENV["ProgramFiles(x86)"]
dir = File.absolute_path("Steam/steamapps/common/RetroArch", ENV["ProgramFiles(x86)"])
if File.directory?(dir) && File.executable?(File.join(dir, RETROARCH_EXE_NAME))
return dir
end
end
fail "RetroArch not found"
end
def retroarch_home
return $retroarch_home ||= treat_path_separator(get_retroarch_home)
end
def retroarch_exename
return $retroarch_exename ||= File.join(retroarch_home, RETROARCH_EXE_NAME)
end
def all_config_dir
return $all_config_dir ||= treat_path_separator(File.join(CONFIG_DIR, "all"))
end
def set_system_name(system_name)
$system_name ||= system_name
end
def system_name
return $system_name
end
def system_config_dir
fail if !system_name
return $system_config_dir ||= treat_path_separator(File.join(CONFIG_DIR, system_name))
end
def system_config_filename
return $system_config_filename ||= File.join(system_config_dir, "retroarch.cfg")
end
def create_system_config_file
fail "Invalid system:#{system_name}" if !system_name || system_name == "all"
dir = File.join(system_config_dir, "saves")
Dir.mkdir(dir) if !File.exist?(dir)
dir = File.join(system_config_dir, "states")
Dir.mkdir(dir) if !File.exist?(dir)
File.open(system_config_filename, "wb:UTF-8") do |ofile|
ofile.puts("# Auto generated by runcommand")
ofile.puts("")
ofile.puts(%[input_remapping_directory = "~/RetroPie-Config/configs/#{system_name}"])
ofile.puts(%[rgui_config_directory = "~/RetroPie-Config/configs/#{system_name}"])
ofile.puts(%[savefile_directory = "~/RetroPie-Config/configs/#{system_name}/saves"])
ofile.puts(%[savestate_directory = "~/RetroPie-Config/configs/#{system_name}/states"])
ofile.puts("")
if ["msx", "pc98", "x68000"].include?(system_name)
cname = File.join(all_config_dir, "retroarch_kbd.cfg")
ofile.puts(%[#include "#{relpath(cname, system_config_dir)}"])
else
cname = File.join(all_config_dir, "retroarch.cfg")
ofile.puts(%[#include "#{relpath(cname, system_config_dir)}"])
end
end
end
def patch_retroarch_manifest
exe_name = retroarch_exename
orig_name = exe_name + ".orig"
mt = File.join(RETROPIE_CONFIG, "etc", "mt.exe")
fail "mt.exe not found: #{mt}" if !File.executable?(mt)
fail "RetroArch is not executable: #{exe_name}" if !File.executable?(exe_name)
if File.exist?(orig_name)
exe_mtime = File.mtime(exe_name)
orig_mtime = File.mtime(orig_name)
if (exe_mtime - (orig_mtime + 60)).abs < 10
return # タイムスタンプ的にOKならショートカットリターン
end
end
temp = Tempfile.new(["retroarch", ".manifest"])
temp.close
cmd = [mt]
cmd += ["-nologo"]
cmd += ["-inputresource:#{exe_name}"]
cmd += ["-out:#{temp.path}"]
win32_system_bg(*cmd)
manifest = REXML::Document.new(File.read(temp.path))
temp.close!
if manifest.elements["/assembly/application/windowsSettings/activeCodePage"]
return # 既にactiveCodePage要素があればリターン
end
$log.info { "Applying: UTF-8 activeCodePage manifest" }
if !manifest.xml_decl || manifest.xml_decl.to_s == ""
manifest << REXML::XMLDecl.new("1.0", "UTF-8", "yes")
end
if !manifest.elements["assembly"]
e = REXML::Element.new("assembly", manifest)
e.add_attribute("manifestVersion", "1.0")
e.add_namespace("urn:schemas-microsoft-com:asm.v1")
end
assembly = manifest.elements["assembly"]
if !assembly.elements["application"]
REXML::Element.new("application", assembly)
end
application = assembly.elements["application"]
if !application.elements["windowsSettings"]
REXML::Element.new("windowsSettings", application)
end
windowsSettings = application.elements["windowsSettings"]
if !windowsSettings.elements["activeCodePage"]
e = REXML::Element.new("activeCodePage", windowsSettings)
e.add_namespace("http://schemas.microsoft.com/SMI/2019/WindowsSettings")
e.text = "UTF-8"
end
temp = Tempfile.new(["retroarch", ".manifest"])
temp.puts(manifest.to_s)
temp.close
orig_mtime = File.mtime(exe_name)
FileUtils.cp(exe_name, orig_name, preserve:true)
cmd = [mt]
cmd += ["-nologo"]
cmd += ["-manifest", temp.path]
cmd += ["-outputresource:#{exe_name}"]
win32_system_bg(*cmd)
temp.close!
File.utime(orig_mtime + 60, orig_mtime + 60, exe_name)
$log.info { "Applied: UTF-8 manifest" }
end
def run_retroarch(core_name=nil, rom_filename=nil)
core_map = {
"lr-beetle-pce-fast" => "mednafen_pce_fast",
"lr-mupen64plus" => "mupen64plus_next",
"lr-np2kai-ex" => "np2kai",
}
if core_name
if core_map[core_name]
core_name = core_map[core_name]
else
core_name = core_name.gsub(/^lr-/, "") # 先頭の lr- を取る
core_name = core_name.gsub("-", "_") # - を _ に置き換える
end
core_name += "_libretro.dll"
$log.info { "Core: #{core_name}" }
create_system_config_file
end
tmplog = Tempfile.new(["retroarch_log", ".log"])
tmplog.close
verbose_log = File.exist?(File.join(File.dirname($PROGRAM_NAME), "retrolog"))
patch_retroarch_manifest
cmd = [retroarch_exename]
cmd += ["--config", system_config_filename]
cmd += ["--log-file", tmplog.path]
cmd += ["--libretro", core_name] if core_name
if rom_filename
cmd += [rom_filename]
else
cmd += ["--menu"]
end
if verbose_log
tmpconf = Tempfile.new(["retroarch_log", ".cfg"])
tmpconf.puts('frontend_log_level = "0"');
tmpconf.puts('libretro_log_level = "0"');
tmpconf.close
cmd += ["--appendconfig", tmpconf.path]
cmd += ["--verbose"]
end
win32_system_fg(*cmd)
File.readlines(tmplog.path, chomp:true, encoding:Encoding::UTF_8).each do |aline|
$log.info { aline }
end
end
def determine_emulator_or_core(rom_filename)
rom_basename = File.basename(rom_filename, ".*")
filename = File.join(all_config_dir, "emulators.cfg")
if File.readable?(filename)
File.open(filename, "rt:UTF-8") do |file|
file.each_line do |aline|
aline.chomp!
if aline =~ /^\s*([^\s_]+)_([^\s]+)\s*=\s*([^\s]+)\s*$/
e_system, e_rom, e_emulator = $1, $2, $3
e_emulator = $1 if e_emulator =~ /^"(.*)"$/
if e_system == system_name && e_rom == rom_basename
return e_emulator
end
end
end
end
end
filename = File.join(system_config_dir, "emulators.cfg")
if File.readable?(filename)
File.open(filename, "rt:UTF-8") do |file|
file.each_line do |aline|
aline.chomp!
if aline =~ /^\s*default\s*=\s*([^\s]+)\s*$/
e_emulator = $1
e_emulator = $1 if e_emulator =~ /^"(.*)"$/
return e_emulator
end
end
end
end
return "(#{system_name})"
end
def main(args)
$log = Logger.new($PROGRAM_NAME + ".log", 2, 128 * 1024)
$log.info { "--------" }
$log.info { "Start: #{$PROGRAM_NAME} #{args.join(" ")}" }
case args.size
when 1
emulator_name = args[0]
case emulator_name
when "retroarch"
$log.info { "Emulator: RetroArch" }
set_system_name("all")
run_retroarch
else
fail "Unknown emulator: #{emulator_name}"
end
when 4
# video_mode = args[0]
# $log.info { "video_mode: #{video_mode}" }
# sys_port = args[1]
# $log.info { "sys_port: #{sys_port}" }
set_system_name(args[2])
$log.info { "System: #{system_name}" }
rom_filename = treat_path_alt_separator(args[3])
$log.info { "Rom: #{rom_filename}" }
emulator_or_core = determine_emulator_or_core(rom_filename)
case emulator_or_core
when /^lr-/
$log.info { "Emulator: RetroArch" }
run_retroarch(emulator_or_core, rom_filename)
when "drastic"
$log.info { "Emulator: DraStic => RetroArch" }
run_retroarch("lr-desmume", rom_filename)
else
fail "Unknown emulator: #{emulator_or_core}"
end
else
fail "Wrong number of arguments (expected 1 or 4)"
end
$log.info { "End" }
return 0
rescue Exception => e
e.backtrace.each_with_index do |t, i|
s = (i == 0) ? "#{t}: #{e.message} (#{e.class.name})" : " from #{t}"
$stderr.puts(s)
$log.error(s)
end
return 1
end
exit main(ARGV)