Repository navigation
Expand file tree
/
Copy pathyakulo
More file actions
executable file
·285 lines (210 loc) · 8.06 KB
/
Copy pathyakulo
File metadata and controls
executable file
·285 lines (210 loc) · 8.06 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
#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
Copyright (c) 2010 Krzysztof Kosyl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import os
import sys
import time
import optparse
import urllib2
import inspect
import subprocess
FILE_PATH = '~/.config/yakulo'
VERSION = '0.2'
class YakuloError(Exception):
pass
def read_lines(name):
if name.startswith(('http://', 'ftp://')):
f = urllib2.urlopen(name)
data = f.read()
f.close()
else:
if '/' in name:
path = os.path.abspath(os.path.expanduser(name))
else:
path = os.path.join(os.path.expanduser(FILE_PATH), name)
f = open(path)
data = f.read()
f.close()
return data.splitlines()
def read_scripts(filenames):
result = [[None, []]]
for filename in filenames:
for line in read_lines(filename):
striped = line.strip()
if striped.startswith('#') or not striped:
pass
elif striped.startswith(':include'):
script = read_scripts(line.split()[1:])
if script[0][0] is None:
result[-1][1].extend(script[0][1])
script = script[1:]
result.extend(script)
elif line.startswith(':tab'):
if result[-1] == [None, []]:
result.pop()
result.append([line.split(' ', 1)[1].strip(), []])
else:
result[-1][1].append(line.strip())
return result
def format_script(script):
for name, commands in script:
print ':tab', name
for command in commands:
print ' %s' % command
def cmd(args):
output = subprocess.Popen([str(i) for i in args], stdout=subprocess.PIPE).communicate()[0]
return output
def cmd_try(args):
try:
retcode = subprocess.call([str(i) for i in args], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
retcode = -1
return retcode
class Yakuake(object):
@staticmethod
def available():
pass
def show(self):
pass
def addSession(self):
pass
def getCurrent(self):
pass
def setName(self, nr, name):
pass
def runCommand(self, nr, command):
pass
class DcopCmdYakuake(Yakuake):
priority = 2.5
@staticmethod
def available():
return cmd_try('dcop yakuake'.split()) == 0
def show(self):
active = cmd('dcop yakuake yakuake-mainwindow#1 isActiveWindow'.split()).strip()
if active == 'false':
cmd('dcop yakuake DCOPInterface slotToggleState'.split())
def addSession(self):
cmd('dcop yakuake DCOPInterface slotAddSession'.split())
def getCurrent(self):
nr = cmd('dcop yakuake DCOPInterface selectedSession'.split())
return int(nr.strip())
def setName(self, nr, name):
cmd('dcop yakuake DCOPInterface slotRenameSession'.split() + [nr, name])
def getName(self, nr):
return cmd('dcop yakuake DCOPInterface slotSessionName'.split() + [nr]).rstrip()
def runCommand(self, nr, command):
cmd('dcop yakuake DCOPInterface slotRunCommandInSession'.split() + [nr, command])
def enterText(self, text):
cmd('dcop klipper klipper setClipboardContents'.split() + [text+ '\n'])
cmd('dcop yakuake DCOPInterface slotPasteClipboard'.split())
def getAll(self):
lst = cmd('dcop yakuake DCOPInterface sessionIdList'.split())
return [int(i) for i in lst.strip().split(',')]
class DbusCmdYakuake(Yakuake):
priority = 1.5
@staticmethod
def available():
return cmd_try('qdbus org.kde.yakuake'.split()) == 0
def show(self):
pass
def addSession(self):
cmd('qdbus org.kde.yakuake /yakuake/sessions addSession'.split())
def getCurrent(self):
nr = cmd('qdbus org.kde.yakuake /yakuake/sessions activeSessionId'.split())
return int(nr.strip())
def setName(self, nr, name):
cmd('qdbus org.kde.yakuake /yakuake/tabs setTabTitle'.split() + [nr, name])
def getName(self, nr):
return cmd('qdbus org.kde.yakuake /yakuake/tabs tabTitle'.split() + [nr]).rstrip()
def runCommand(self, nr, command):
tid = cmd('qdbus org.kde.yakuake /yakuake/sessions terminalIdsForSessionId'.split() + [nr]).split(',')[0].strip()
cmd('qdbus org.kde.yakuake /yakuake/sessions runCommandInTerminal'.split() + [tid, command])
def enterText(self, text):
nr = cmd('qdbus org.kde.yakuake /yakuake/sessions activeSessionId'.split())
tid = cmd('qdbus org.kde.yakuake /yakuake/sessions terminalIdsForSessionId'.split() + [nr]).split(',')[0]
cmd('qdbus org.kde.yakuake /yakuake/sessions runCommandInTerminal'.split() + [tid, text])
def getAll(self):
return []
def get_class():
classes = inspect.getmembers(sys.modules[__name__], inspect.isclass)
classes = [(cls.priority, cls) for cls_name, cls in classes if hasattr(cls, 'priority')]
classes.sort()
klass = None
for priority, cls in classes:
if cls.available():
klass = cls
break
if klass is None:
raise YakuloError('No Yakuake is running')
else:
return klass()
def load(yaku, script, new):
yaku.show()
for name, commands in script:
if new:
yaku.addSession()
new = True
nr = yaku.getCurrent()
if name is not None:
yaku.setName(nr, name)
for command in commands:
if command.startswith('yak-sleep'):
sleep = float((command.split() + ['1.0'])[1])
time.sleep(sleep)
elif command.startswith('yak-enter'):
yaku.enterText(command.split(' ', 1)[-1])
else:
yaku.runCommand(nr, command)
def main():
parser = optparse.OptionParser(usage="usage: %prog [options] [scripts]")
parser.version = '%prog version ' + VERSION
parser.add_option("-v", "--version", action="version", help="show version")
parser.add_option("-p", "--parse",
action="store_true",
dest="parse",
default=False,
help="print parsed script to stdout and exit"
)
parser.add_option("-n", "--new",
action="store_true",
dest="new",
default=False,
help="create new session for first tabs"
)
(options, args) = parser.parse_args()
names = ['default'] if len(args) == 0 else args
script = read_scripts(names)
yaku = get_class()
if options.parse:
format_script(script)
else:
if not options.new:
try:
pid = os.fork()
except OSError, e:
raise Exception, "%s [%d]" % (e.strerror, e.errno)
if pid != 0:
os._exit(0)
load(yaku, script, options.new)
if __name__ == '__main__':
try:
main()
except YakuloError, e:
print >> sys.stderr, e.args[0]