Source

fsgamer / fsgamer / utils.py

  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
import json
import subprocess
import os
import shlex
import sys
import signal
import time
import optparse
import traceback
from pipes import quote


import gettext
from gettext import gettext as _
gettext.textdomain('fsgamer')

from fsgamer_lib import get_version, get_data_path
VERBOSE = False

class DependencyError(Exception): pass

#BINPATH = os.environ.get("FSGAMER_BIN", sys.argv[0])

BINPATH = os.path.abspath(sys.argv[0])

# Quick hack for during development using quickly

#QUICKLY_RUN_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(
#                                os.path.realpath(__file__)))), "quicklyrun.sh")
#if os.path.exists(QUICKLY_RUN_PATH):
#    BINPATH = QUICKLY_RUN_PATH


HOMEDIR = os.path.expanduser("~")

TITLE_TRANS = ''.join(chr(c) if chr(c).isupper() or chr(c).islower() else '_' for c in range(256))


####################################################################
# Terminal output functions
# A few functions for making output to the terminal neater
####################################################################
class Term:
    bold = "\033[1m"
    reset= "\033[0;0m"
    purple = '\033[95m'
    blue = '\033[94m'
    green = '\033[92m'
    yellow = '\033[93m'
    red = '\033[91m'
    Bold = staticmethod(lambda s: Term.bold + s + Term.reset)
    Blue = staticmethod(lambda s: Term.blue + s + Term.reset)
    Yellow = staticmethod(lambda s: Term.yellow + s + Term.reset)
    Green = staticmethod(lambda s: Term.green + s + Term.reset)
    Red = staticmethod(lambda s: Term.red + s + Term.reset)
    Purple = staticmethod(lambda s: Term.purple + s + Term.reset)

def warning(msg):
    sys.stderr.write(Term.Yellow("Warning: ") + Term.Bold(msg) + "\n")

def notice(msg):
    if VERBOSE:
        sys.stdout.write(Term.Blue("Note: ") + Term.Bold(msg) + "\n")

def trace(msg):
    if int(VERBOSE) > 1:
        sys.stdout.write(Term.Bold(msg) + "\n")

def error(type, info=None, report=False):
    if info:
        msg = {
            'dependency': "The package '%s' is not installed.\n"+
                    "Try sudo apt-get install %s to correct this problem.",
            'xorg': "Something went wrong with Xorg: %s",
            }[type].replace('%s', str(info))

        sys.stderr.write("\n-----------------------------\n")
        sys.stderr.write(Term.Red("Fatal Error: ") +
                Term.Bold('%s'%type.capitalize() + '\n' + msg))
    else:
        sys.stderr.write(Term.Red("Fatal Exception"))
        traceback.print_exc()

    if report or not info:
        sys.stderr.write(Term.Green(
            "\nPlease report this issue to at http://michaelb.org/fsgamer/\n"))
    sys.stderr.write("\n-----------------------------\n")
    sys.exit(1)

def _alphanum(s):
    return s.strip().translate(TITLE_TRANS).replace("_", "")

class shellbuilder:
    XINIT_SCRIPT = '''
        DISPLAY=:%(display)i.0
        exec %(xinit)s %(cmd)s  -- :%(display)i %(extra)s
        '''.strip().replace('    ', '')
    @staticmethod
    def xinit(cmd, display, opts):

        xinit_path = shell_run.which("xinit")
        cklaunch_path = shell_run.which("ck-launch-session")

        xinit = "%s %s" % (xinit_path, cklaunch_path)

        d = {
            'xinit': xinit,
            'display': display,
            'cmd': cmd.strip(),
            'extra': '',
        }

        if opts.get('xorg_conf'):
            fullpath = os.path.join('etc', 'X11', opts['xorg_conf'])
            if not os.path.exists(fullpath):
                print "ERROR: Xorg conf specified does not exist: ", opts['xorg_conf']

            # Pass its raw format, because config already only looks there suppposedly
            # NOTE: need to test, is this -config or -xf86config
            d['extra'] = '-xf86config %s' % quote(opts['xorg_conf'])

        # Wrap script
        script = shellbuilder.XINIT_SCRIPT % d

        return script

    FSGWM_SCRIPT = "%(base)s --wm --exec=%(exec)s --opts=%(opts)s"
    @staticmethod
    def fsgwm(cmd, opts, openbox=True):
        """
        Generates path to run windows manager, auto-execing given command path
        """
        import openbox
        d = {
            'exec': cmd,
            'opts': opts,
        }

        if openbox and openbox.ENABLED:
            d['openbox'] = None
        else:
            d['wm'] = None

        return unparse_options(d)

    @staticmethod
    def xinit_fsgwm(cmd, display, opts):
        """
        This is the main function where all the magic is:

        It runs (blocking) a command using the FSGamer windows manager in a new
        xinit buffer wrapped around ck-launch-session, passing to the windows
        manager (via JSON) the dictionary of opts
        """
        script = []

        if opts.get('notifications_tts'):
            # If we have TTS notifications enabled, then add that to the script
            script.append(unparse_options({'tts': None}) + " &")

        #if not opts.get('keep_going'):
        #    # Run kill-pact process to kill everything if the child process
        #    # fails to start
        #    d = {'killpact': None, 'exec': cmd}
        #    script.append(unparse_options(d) + " &")

        script.append(
                shellbuilder.xinit(shellbuilder.fsgwm(cmd, opts), display, opts)
            )

        return "\n".join(script)
        #return self("\n".join(script))
        #return subprocess.Popen(script_args, shell=True, bufsize=-1)


TMP_DIR = "/tmp/fsgamer_%i/"
def tmp_file_path(path):
    return os.path.join(TMP_DIR%os.getuid(), path)

def write_tmp_file(path, data):
    path = os.path.join(TMP_DIR%os.getuid(), path)
    dirpath = os.path.dirname(path)
    try:
        os.makedirs(dirpath)
        os.chmod(dirpath, 0777)
    except OSError:
        pass

    open(path, "w").write(data)
    return path


class ShellRun:
    TMP_DIR = "/tmp/fsgamer_%i/run/"
    def __init__(self):
        self.processes = []
        self.defunct = []

    def killall(self):
        print "GOING TO TRY KILLING IT ALL", self.processes
        os.killpg(0, signal.SIGKILL) # kill all processes in my group
        for process in self.processes:
            print "Killing ", process
            process.terminate()

        time.sleep(2)
        for process in self.processes:
            process.kill()

        time.sleep(2)
        for process in self.processes:
            print "Waiting for ", process
            process.wait()
        self.defunct.extend(self.processes)
        self.processes = []
        self.process.wait()

    def replace_killall_fsgamer(self):
        killall = self.which('killall')
        os.execv(killall, [killall, "fsgamer"])

    def replace_kill_everything(self, exe=None):
        hitlist = [
                    "ck-launch-session",
                    "openbox",
                    "fsgamer_",
                    BINPATH,
                ]

        if exe:
            hitlist.append(exe)

        processes = self.get_processes()

        pid_hitlist = []
        for pid, cmdline in processes.iteritems():
            for item in hitlist:
                if item in cmdline:
                    pid_hitlist.append(pid)

        script = """
            killall fsgamer
            kill IDS
            sleep 5
            kill -9 IDS
        """.replace("IDS", " ".join(map(str, pid_hitlist)))

        if not pid_hitlist:
            return
        self(script, replace=True)

    def sh_from_script(self, script, fake_shell=False):
        tmp_dir = self.TMP_DIR % os.getuid()
        script_text = "#!/bin/bash\n%s" % script

        # Give it our own name so that its easier to spot in the process list
        fn = os.path.join(str(len(script)), "fsgamer")

        path = os.path.join(tmp_dir, fn)

        # If we are just getting a name, and not actually writing it out
        if fake_shell:
            return path

        try:
            os.makedirs(os.path.dirname(path))
        except OSError:
            pass

        open(path, "w").write(script_text)

        os.chmod(path, 0777)
        assert os.path.exists(path)

        return path

    def __call__(self, script, replace=False):
        path = self.sh_from_script(script)
        if not replace:
            process = subprocess.Popen(path,
                                    bufsize=-1)
            print "New process: ", process.pid
            self.processes.append(process)
            print "THESE ARE MY PROCESSES", self.processes
            return process
        else:
            print "----------------------------------------------"
            print path
            print "=============================================="
            print script
            print "----------------------------------------------"
            os.execv(path, [path])
        #script_args = shlex.split(script)
        #return subprocess.Popen(script_args, shell=True, bufsize=-1)

    _which_cache = {}
    def which(self, cmd):
        if cmd in self._which_cache:
            return self._which_cache[cmd]

        try:
            path = subprocess.check_output("which %s"%cmd, shell=True)
        except subprocess.CalledProcessError:
            path = None
        else:
            path = path.strip()

        if not path:
            return path

        self._which_cache[cmd] = path
        return path

    def get_processes(self):
        pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
        r = {}
        for pid in pids:
            path = os.path.join('/proc', pid, 'cmdline')
            try:
                r[pid] = open(path, 'rb').read()
            except OSError: pass
            except IOError: pass
        return r

    def is_running(self, search, exact=False):
        processes = self.get_processes()
        for pid, cmd in processes.iteritems():
            if exact:
                if _alphanum(search) == _alphanum(cmd):
                    return pid
            elif search in cmd:
                return pid
        return False

    def return_when_stopped_running(self, exe):
        found_pid = None

        while not found_pid:
            time.sleep(10)
            processes = self.get_processes()
            found_pid = self.is_running(exe, exact=True)

        pid_path = os.path.join('/proc', found_pid)

        while True:
            if not os.path.exists(pid_path):
                # process ended!
                return
            time.sleep(3)

shell_run = ShellRun()

def unparse_options(dct, command=None, use_equals=True):
    args = [command or BINPATH]
    for item, val in dct.items():
        if val is None:
            args.append('--%s'%item)
            continue

        if isinstance(val, dict):
            val = json.dumps(val)

        if use_equals:
            args.append("--%s=%s" % (item, quote(str(val))))
        else:
            args.append("--%s %s" % (item, quote(str(val))))

    return " ".join(args)

def set_verbose(val=True):
    global VERBOSE
    VERBOSE = val

def parse_options(string=None):
    """Support for command line options"""
    parser = optparse.OptionParser(version="%%prog %s" % get_version())

    parser.add_option(
        "-v", "--verbose", action="count", dest="verbose",
        help=_("Show debug messages (-vv debugs fsgamer_lib also)"))

    parser.add_option(
        "-e", "--exec",   dest="exe", metavar="CMD",
        help=_("Executes given shell command in a new xsession"))

    parser.add_option(
        "-d", "--desktop",  dest="desktop", metavar="FILE.desktop",
        help=_("Path to desktop file responsible to enable GUI"))

    parser.add_option(
        "-o", "--opts",   dest="opts", metavar="JSON",
        help=_("JSON opts format for more controller options"))

    parser.add_option(
        "-w", "--wm", action="store_true", dest="wm",
        help=_("Launch custom windows manager, in current X session, auto-running exec"))

    parser.add_option(
        "-b", "--openbox", action="store_true", dest="openbox",
        help=_("Launch openbox, in current X session, auto-running exec"))

    parser.add_option(
        "-t", "--tts", action="store_true", dest="tts",
        help=_("Speaks notifications via TTS"))

    parser.add_option(
        "-K", "--killall", action="store_true", dest="killall",
        help=_("Kills all processes named 'fsgamer', 'openbox' and exec"))

    parser.add_option(
        "-p", "--killpact", action="store_true", dest="killpact",
        help=_("Killall when exec stops running"))

    if string:
        (options, args) = parser.parse_args(shlex.split(string))
    else:
        (options, args) = parser.parse_args(sys.argv)

    if options.opts:
        # Should be a JSON object at this point
        try:
            print "options.opts", options.opts
            options.opts = json.loads(options.opts)
        except:
            print "Uh oh couldn't load options..."
            options.opts = {}

    return options, args