Completed
Push — master ( e78923...5c165f )
by timothy
01:28
created

_stringify_key()   A

Complexity

Conditions 4

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
dl 0
loc 10
rs 9.2
c 3
b 0
f 0
1
'''
2
some of these should go into neovim python client
3
'''
4
from __future__ import print_function
5
6
import os
7
import time
8
from subprocess import *
9
from threading import Thread
10
import shlex
11
import string
12
import random
13
from functools import wraps
14
import sched
15
import _thread as thread
16
import timeit
17
18
from neovim import attach
19
20
def attach_socket(path=None):
21
    '''does it auto'''
22
    def open_nvim():
23
        proc = Popen('NVIM_LISTEN_ADDRESS=/tmp/nvim nvim',
24
                    stdin=PIPE, stdout=PIPE, shell=True)
25
        proc.communicate()
26
27
    # THIS IS DOESNT WORK UNRELIBALE 
28
    #path = os.environ.get('NVIM_LISTEN_ADDRESS')
29
    if not path:
30
        print('threading')
31
        t = Thread(target=open_nvim)
32
        t.start()
33
        #todo make this give a random path
34
        return attach('socket', path='/tmp/nvim')
35
    else:
36
        print('attaching socket')
37
        return attach('socket', path=path)
38
39
40
def attach_child():
41
    return attach('child', argv=['nvim', '--embed'])
42
43
44
def attach_headless(nvim_args=None, path=None):
45
    if not path:
46
        path = '/tmp/nvim' + rand_str(8)
47
    os.environ['NVIM_LISTEN_ADDRESS'] = path
48
    dnull = open(os.devnull)
49
    # TODO WHY USE SHLEX???
50
    cmd = shlex.split('nvim --headless')
51
    if nvim_args:
52
        cmd.extend(nvim_args)
53
    proc = Popen(cmd,
54
            stdin=dnull,
55
            stdout=dnull,
56
            stderr=dnull)
57
    dnull.close()
58
    while proc.poll() or proc.returncode is None:
59
        try:
60
            nvim = attach('socket', path=path)
61
            break
62
        except IOError:
63
            # Socket not yet ready
64
            time.sleep(0.05)
65
66
    return nvim
67
68
69
def rand_str(length):
70
    '''returns a random string of length'''
71
    chars = []
72
    for i in range(length):
73
        chars.append(random.choice(string.ascii_letters))
74
    return ''.join(char for char in chars)
75
76
77
def _stringify_key(key, state):
78
    send = []
79
    if state == 'Shift':
80
        send.append('S')
81
    elif state == 'Ctrl':
82
        send.append('C')
83
    elif state =='Alt':
84
        send.append('A')
85
    send.append(key)
86
    return '<' + '-'.join(send) + '>'
87
88
89
def _split_color(n):
90
    return ((n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff,)
91
92
93
def _invert_color(r, g, b):
94
    return (255 - r, 255 - g, 255 - b,)
95
96
97
def _stringify_color(r, g, b):
98
    return '#{0:0{1}x}'.format((r << 16) + (g << 8) + b, 6)
99
100
101
def debug_echo(func):
102
    '''used on method to simply print the function name and
103
    parameters if self.debug_echo = True,
104
    the function will not execute'''
105
    @wraps(func)
106
    def deco(*args, **kwargs):
107
        try:
108
            debug = args[0].debug_echo
109
        except AttributeError:
110
            debug = False
111
        if debug:
112
            if len(args) == 1:
113
                to_print = []
114
            else:
115
                to_print = args[1:]
116
            print(func.__name__, repr(to_print), **kwargs)
117
118
        return func(*args, **kwargs)
119
    return deco
120
121
122
def delay_call(seconds):
123
    '''Decorator to delay the runtime of your function,
124
    each succesive call to function will refresh the timer,
125
    canceling any previous functions
126
    '''
127
    _scheduler = sched.scheduler(timeit.default_timer,
128
                                 time.sleep)
129
    def delayed_func(func):
130
        @wraps(func)
131
        def modded_func(*args, **kwrds):
132
            if len(_scheduler.queue) == 1:
133
                _scheduler.enter(seconds, 1, func, args, kwrds)
134
                _scheduler.cancel(_scheduler.queue[0])
135
            else:
136
                _scheduler.enter(seconds, 1, func, args, kwrds)
137
                thread.start_new_thread(_scheduler.run, ())
138
        thread.start_new_thread(_scheduler.run, ())
139
        modded_func.scheduler = _scheduler
140
        return modded_func
141
    return delayed_func
142