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
|
#!/usr/bin/python3
# encoding=utf-8
# game-data-packager Gtk launcher stub. See doc/launcher.mdwn for design
# Copyright © 2015-2016 Simon McVittie <smcv@debian.org>
# SPDX-License-Identifier: GPL-2.0-or-later
import fnmatch
import logging
import os
import traceback
from contextlib import suppress
import gi
gi.require_version('Gtk', '4.0')
from gi.repository import (GLib, GObject)
from gi.repository import Gtk
from gdp_launcher_base import (
Launcher,
RUNTIME_BUILT,
)
logger = logging.getLogger('game-data-packager.launcher')
if os.environ.get('GDP_DEBUG'):
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
class IniEditor:
def __init__(self, edits):
self.lines = []
self.edits = edits
self.__section = None
self.__section_lines = []
self.__sections = set()
def load(self, reader):
# Simple INI parser. Not using ConfigParser because Unreal
# uses duplicate keys within sections, and we want to preserve
# comments, blank lines etc.
self.__section = None
self.__section_lines = []
self.__sections = set()
for line in reader:
line = line.rstrip('\r\n')
if line.startswith('[') and line.endswith(']'):
self.__end_section()
self.__section = line[1:-1]
self.__section_lines.append(line)
self.__end_section()
for edit in self.edits:
if edit['section'] not in self.__sections:
self.__section = edit['section']
self.__section_lines = ['[%s]' % edit['section']]
self.__end_section()
def __end_section(self):
self.__sections.add(self.__section)
for edit in self.edits:
if edit['section'] != self.__section:
continue
logger.debug('editing %s', self.__section)
extra_lines = []
for k, v in sorted(edit.get('replace_key', {}).items()):
logger.debug('replacing %s with %s', k, v)
self.__section_lines = [l for l in self.__section_lines
if not l.startswith(k + '=')]
extra_lines.append('%s=%s' % (k, v))
for pattern in sorted(edit.get('delete_matched', [])):
logger.debug('deleting lines matching %s', pattern)
self.__section_lines = [l for l in self.__section_lines
if not fnmatch.fnmatchcase(l, pattern)]
for pattern in edit.get('comment_out_matched', []):
logger.debug('commenting out lines matching %s', pattern)
for i in range(len(self.__section_lines)):
if fnmatch.fnmatchcase(self.__section_lines[i], pattern):
self.__section_lines[i] = ';' + self.__section_lines[i]
self.__section_lines.insert(i, '; ' +
edit['comment_out_reason'])
for append in edit.get('append_unique', []):
logger.debug('appending unique line %s', append)
for line in self.__section_lines:
if line == append:
break
else:
extra_lines.append(append)
i = len(self.__section_lines) - 1
while i >= 0:
if self.__section_lines[i]:
# _s_l[i] is the last non-empty line, insert after it
self.__section_lines[i + 1:i + 1] = extra_lines
break
i -= 1
else:
# no non-empty lines, insert after the section-opening heading
self.__section_lines[1:1] = extra_lines
self.lines.extend(self.__section_lines)
self.__section_lines = []
self.__section = None
def save(self, writer):
for line in self.lines:
print(line, file=writer)
class FullLauncher(Launcher):
def set_id(self):
self.keyfile = GLib.KeyFile()
desktop = os.path.join(RUNTIME_BUILT, self.id + '.desktop')
if os.path.exists(desktop):
self.keyfile.load_from_file(desktop, GLib.KeyFileFlags.NONE)
else:
self.keyfile.load_from_data_dirs(
'applications/%s.desktop' % self.id,
GLib.KeyFileFlags.NONE)
self.name = self.keyfile.get_string(GLib.KEY_FILE_DESKTOP_GROUP,
GLib.KEY_FILE_DESKTOP_KEY_NAME)
logger.debug('Name: %s', self.name)
GLib.set_application_name(self.name)
self.icon_name = self.keyfile.get_string(GLib.KEY_FILE_DESKTOP_GROUP,
GLib.KEY_FILE_DESKTOP_KEY_ICON)
logger.debug('Icon: %s', self.icon_name)
self.expansion_name = self.args.expansion
try:
override_id = self.keyfile.get_string(GLib.KEY_FILE_DESKTOP_GROUP,
'X-GameDataPackager-ExpansionFor')
except GLib.Error:
pass
else:
if self.expansion_name is None:
self.expansion_name = self.id
if self.expansion_name.startswith(override_id + '-'):
self.expansion_name = self.expansion_name[len(override_id) + 1:]
self.id = override_id
def exec_game(self, _unused=None):
if self.id == 'ut99':
dest = os.path.join(self.dot_directory, 'System64')
with suppress(FileExistsError):
os.symlink('System', dest)
if self.expand_tokens['UT99System'] == 'System64':
libdirs = [
'/usr/lib/x86_64-linux-gnu',
'/usr/lib64',
'/usr/lib',
]
else:
libdirs = [
'/usr/lib/i386-linux-gnu',
'/usr/lib32',
'/usr/lib',
]
os.makedirs(
os.path.join(self.dot_directory, 'System'),
exist_ok=True,
)
for d in libdirs:
f = os.path.join(d, 'libmpg123.so.0')
if os.path.exists(f):
dest = os.path.join(
self.dot_directory,
'System',
'libmpg123.so',
)
with suppress(FileNotFoundError):
os.remove(dest)
os.symlink(f, dest)
break
# Edit before copying, so that we can detect whether this is
# the first run or not
for ini, details in self.data.get('edit_unreal_ini', {}).items():
assert self.dot_directory is not None
target = os.path.join(self.dot_directory, ini)
encoding = details.get('encoding', 'windows-1252')
if os.path.exists(target):
first_time = False
try:
reader = open(target, encoding='utf-16')
reader.readline()
except:
reader = open(target, encoding=encoding)
else:
reader.seek(0)
else:
first_time = True
if os.path.lexists(target):
logger.info('Removing dangling symlink %s', target)
os.remove(target)
for base in self.base_directories:
source = os.path.join(base, ini)
if os.path.exists(source):
try:
reader = open(source, encoding='utf-16')
reader.readline()
except:
reader = open(source, encoding=encoding)
else:
reader.seek(0)
break
else:
raise AssertionError('Required file %s not found', ini)
if first_time:
edits = details.get('once', []) + details.get('always', [])
else:
edits = details.get('always', [])
logger.debug('%s', edits)
editor = IniEditor(edits)
with reader:
editor.load(reader)
d = os.path.dirname(target)
if d:
logger.info('Creating directory: %s', d)
os.makedirs(d, exist_ok=True)
with open(target, 'w', encoding=encoding,
newline=details.get('newline', '\n')) as writer:
editor.save(writer)
super().exec_game()
def write_confirm_binary_only_stamp(self):
open(self.warning_stamp, 'a').close()
def __init__(self):
super().__init__()
# Migrate old directories to new, e.g. ~/.loki/ut -> ~/.utpg
for old in self.old_dot_directories:
new = self.dot_directory
assert new is not None
os.makedirs(os.path.dirname(new), exist_ok=True)
have_old = os.path.exists(old)
have_new = os.path.exists(new)
if have_old and not have_new:
logger.debug('Migrating from %s to %s', old, new)
try:
os.rename(old, new)
except OSError as e:
logger.debug(
'Unable to rename, falling back to symlink: %s',
e,
)
rel = os.path.relpath(old, start=os.path.dirname(new))
logger.debug('Creating symlink %s -> %s', new, rel)
os.symlink(rel, new)
self.window = Gtk.Window()
self.window.set_default_size(600, 300)
self.window.set_title(self.name)
self.window.set_icon_name(self.icon_name)
self.grid = Gtk.Grid(row_spacing=6, column_spacing=6,
margin_top=12, margin_bottom=12, margin_start=12, margin_end=12)
self.window.set_child(self.grid)
image = Gtk.Image.new_from_icon_name(self.icon_name)
image.set_pixel_size(48)
image.set_valign(Gtk.Align.START)
self.grid.attach(image, 0, 0, 1, 1)
self.text_view = Gtk.TextView(editable=False, cursor_visible=False,
hexpand=True, vexpand=True, wrap_mode=Gtk.WrapMode.WORD,
left_margin=6, right_margin=6)
try:
self.text_view.set_bottom_margin(6)
self.text_view.set_top_margin(6)
except:
logger.warn('You are using an old version of pygobject')
self.grid.attach(self.text_view, 1, 0, 1, 1)
subgrid = Gtk.Grid(column_spacing=6, column_homogeneous=True,
halign=Gtk.Align.END)
cancel_button = Gtk.Button.new_with_label('Cancel')
cancel_button.connect('clicked', lambda _: self.window.close())
subgrid.attach(cancel_button, 0, 0, 1, 1)
self.check_box = Gtk.CheckButton.new_with_label("I'll be careful")
self.check_box.set_hexpand(True)
self.grid.attach(self.check_box, 0, 1, 2, 1)
self.ok_button = Gtk.Button.new_with_label('Run')
self.ok_button.set_sensitive(False)
subgrid.attach(self.ok_button, 1, 0, 1, 1)
self.grid.attach(subgrid, 0, 2, 2, 1)
def run_error(self, message):
self.show_error(message)
context = GLib.MainContext.default()
while len(Gtk.Window.get_toplevels()) > 0:
context.iteration(True)
def show_error(self, message):
self.text_view.get_buffer().set_text(message)
self.ok_button.set_sensitive(False)
self.check_box.hide()
self.window.present()
def run_confirm_binary_only(self):
self.text_view.get_buffer().set_text(
self.load_text('confirm-binary-only.txt',
'Binary-only game, we cannot fix bugs or security '
'vulnerabilities!'))
self.check_box.bind_property('active', self.ok_button, 'sensitive',
GObject.BindingFlags.SYNC_CREATE)
self.ok_button.connect('clicked',
lambda _: self.__confirm_binary_only_cb())
self.window.present()
context = GLib.MainContext.default()
while len(Gtk.Window.get_toplevels()) > 0:
context.iteration(True)
def __confirm_binary_only_cb(self):
try:
self.write_confirm_binary_only_stamp()
self.exec_game()
except:
self.show_error(traceback.format_exc())
if __name__ == '__main__':
logging.basicConfig()
FullLauncher().main()
|