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
|
from time import time
import os
import cPickle as pickle
import gio
import gobject
from kupfer import pretty, config
from kupfer import scheduler
from kupfer import desktop_launch
from kupfer.ui import uievents
from kupfer import terminal
from kupfer.desktop_launch import SpawnError
## NOTE: SpawnError *should* be imported from this module
try:
import wnck
wnck.set_client_type(wnck.CLIENT_TYPE_PAGER)
except ImportError, e:
pretty.print_info(__name__, "Disabling window tracking:", e)
wnck = None
default_associations = {
"evince" : "Document Viewer",
"file-roller" : "File Roller",
#"gedit" : "Text Editor",
"gnome-keyring-manager" : "Keyring Manager",
"nautilus-browser" : "File Manager",
"rhythmbox" : "Rhythmbox Music Player",
}
def application_id(app_info, desktop_file=None):
"""Return an application id (string) for GAppInfo @app_info"""
app_id = app_info.get_id()
if not app_id:
app_id = desktop_file or ""
if app_id.endswith(".desktop"):
app_id = app_id[:-len(".desktop")]
return app_id
def launch_application(app_info, files=(), uris=(), paths=(), track=True,
activate=True, desktop_file=None, screen=None):
"""
Launch @app_rec correctly, using a startup notification
you may pass in either a list of gio.Files in @files, or
a list of @uris or @paths
if @track, it is a user-level application
if @activate, activate rather than start a new version
@app_rec is either an GAppInfo or (GAppInfo, desktop_file_path) tuple
Raises SpawnError on failed program start.
"""
assert app_info
if paths:
files = [gio.File(p) for p in paths]
if uris:
files = [gio.File(p) for p in uris]
svc = GetApplicationsMatcherService()
app_id = application_id(app_info, desktop_file)
if activate and svc.application_is_running(app_id):
svc.application_to_front(app_id)
return True
# An launch callback closure for the @app_id
def application_launch_callback(argv, pid, notify_id, files, timestamp):
is_terminal = terminal.is_known_terminal_executable(argv[0])
if not is_terminal:
svc.launched_application(app_id, pid)
if track:
launch_callback = application_launch_callback
else:
launch_callback = None
try:
desktop_launch.launch_app_info(app_info, files,
timestamp=uievents.current_event_time(),
desktop_file=desktop_file,
launch_cb=launch_callback,
screen=screen)
except SpawnError:
raise
return True
def application_is_running(app_id):
svc = GetApplicationsMatcherService()
return svc.application_is_running(app_id)
def application_close_all(app_id):
svc = GetApplicationsMatcherService()
return svc.application_close_all(app_id)
class ApplicationsMatcherService (pretty.OutputMixin):
"""Handle launching applications and see if they still run.
This is a learning service, since we have no first-class application
object on the Linux desktop
"""
def __init__(self):
self.register = {}
self._get_wnck_screen_windows_stacked()
scheduler.GetScheduler().connect("finish", self._finish)
self._load()
@classmethod
def _get_wnck_screen_windows_stacked(cls):
if not wnck:
return ()
screen = wnck.screen_get_default()
return screen.get_windows_stacked()
def _get_filename(self):
# Version 1: Up to incl v203
# Version 2: Do not track terminals
version = 2
return os.path.join(config.get_cache_home(),
"application_identification_v%d.pickle" % version)
def _load(self):
reg = self._unpickle_register(self._get_filename())
self.register = reg if reg else default_associations
# pretty-print register to debug
if self.register:
self.output_debug("Learned the following applications")
self.output_debug("\n{\n%s\n}" % "\n".join(
(" %-30s : %s" % (k,v)
for k,v in self.register.iteritems())
))
def _finish(self, sched):
self._pickle_register(self.register, self._get_filename())
def _unpickle_register(self, pickle_file):
try:
pfile = open(pickle_file, "rb")
except IOError, e:
return None
try:
source = pickle.loads(pfile.read())
assert isinstance(source, dict), "Stored object not a dict"
self.output_debug("Reading from %s" % (pickle_file, ))
except (pickle.PickleError, Exception), e:
source = None
self.output_info("Error loading %s: %s" % (pickle_file, e))
return source
def _pickle_register(self, reg, pickle_file):
output = open(pickle_file, "wb")
self.output_debug("Saving to %s" % (pickle_file, ))
output.write(pickle.dumps(reg, pickle.HIGHEST_PROTOCOL))
output.close()
return True
def _store(self, app_id, window):
# FIXME: Store the 'res_class' name?
application = window.get_application()
store_name = application.get_name()
self.register[app_id] = store_name
self.output_debug("storing application", app_id, "as", store_name)
def _has_match(self, app_id):
return app_id in self.register
def _is_match(self, app_id, window):
application = window.get_application()
res_class = window.get_class_group().get_res_class()
reg_name = self.register.get(app_id)
if reg_name and reg_name in (application.get_name(), res_class):
return True
if app_id in (application.get_name().lower(), res_class.lower()):
return True
return False
def launched_application(self, app_id, pid):
if self._has_match(app_id):
return
timeout = time() + 15
gobject.timeout_add_seconds(2, self._find_application, app_id, pid, timeout)
# and once later
gobject.timeout_add_seconds(30, self._find_application, app_id, pid, timeout)
def _find_application(self, app_id, pid, timeout):
if self._has_match(app_id):
return False
#self.output_debug("Looking for window for application", app_id)
for w in self._get_wnck_screen_windows_stacked():
app = w.get_application()
app_pid = app.get_pid()
if not app_pid:
app_pid = w.get_pid()
if app_pid == pid:
self._store(app_id, w)
return False
if time() > timeout:
return False
return True
def application_name(self, app_id):
if not self._has_match(app_id):
return None
return self.register[app_id]
def application_is_running(self, app_id):
for w in self._get_wnck_screen_windows_stacked():
if (w.get_application() and self._is_match(app_id, w) and
w.get_window_type() == wnck.WINDOW_NORMAL):
return True
return False
def get_application_windows(self, app_id):
application_windows = []
for w in self._get_wnck_screen_windows_stacked():
if (w.get_application() and self._is_match(app_id, w) and
w.get_window_type() == wnck.WINDOW_NORMAL):
application_windows.append(w)
return application_windows
def application_to_front(self, app_id):
application_windows = self.get_application_windows(app_id)
if not application_windows:
return False
etime = uievents.current_event_time()
# if True, focus app's all windows on the same workspace
# if False, focus only one window (in cyclical manner)
focus_all = True
if focus_all:
return self._to_front_application_style(application_windows, etime)
else:
return self._to_front_single(application_windows, etime)
def _to_front_application_style(self, application_windows, evttime):
workspaces = {}
cur_screen = application_windows[0].get_screen()
cur_workspace = cur_screen.get_active_workspace()
def visible_window(window):
return (window.get_window_type() == wnck.WINDOW_NORMAL and
window.is_visible_on_workspace(cur_workspace))
def normal_window(window):
return window.get_window_type() == wnck.WINDOW_NORMAL
## get all visible windows in stacking order
vis_windows = filter(visible_window,
self._get_wnck_screen_windows_stacked())
## sort windows into "bins" by workspace
for w in filter(normal_window, application_windows):
wspc = w.get_workspace() or cur_workspace
workspaces.setdefault(wspc, []).append(w)
cur_wspc_windows = workspaces.get(cur_workspace, [])
# make a rotated workspace list, with current workspace first
idx = cur_workspace.get_number()
all_workspaces = cur_screen.get_workspaces()
all_workspaces[:] = all_workspaces[idx:] + all_workspaces[:idx]
# check if the application's window on current workspace
# are the topmost
focus_windows = []
if (cur_wspc_windows and
set(vis_windows[-len(cur_wspc_windows):]) != set(cur_wspc_windows)):
focus_windows = cur_wspc_windows
## if the topmost window is already active, take another
if focus_windows[-1:] == vis_windows[-1:]:
focus_windows[:] = focus_windows[:-1]
else:
# all windows are focused, find on next workspace
for wspc in all_workspaces[1:]:
focus_windows = workspaces.get(wspc, [])
if focus_windows:
break
else:
# no windows on other workspaces, so we rotate among
# the local ones
focus_windows = cur_wspc_windows[:1]
self._focus_windows(focus_windows, evttime)
def _to_front_single(self, application_windows, evttime):
# bring the first window to front
for window in application_windows:
self._focus_windows([window], evttime)
return
def _focus_windows(self, windows, evttime):
for window in windows:
# we special-case the desktop
# only show desktop if it's the only window
if window.get_name() == "x-nautilus-desktop":
if len(windows) == 1:
screen = wnck.screen_get_default()
screen.toggle_showing_desktop(True)
else:
continue
wspc = window.get_workspace()
if wspc:
wspc.activate(evttime)
window.activate_transient(evttime)
def application_close_all(self, app_id):
application_windows = self.get_application_windows(app_id)
evttime = uievents.current_event_time()
for w in application_windows:
if not w.is_skip_tasklist():
w.close(evttime)
_appl_match_service = None
def GetApplicationsMatcherService():
"""Get the (singleton) ApplicationsMatcherService"""
global _appl_match_service
if not _appl_match_service:
_appl_match_service = ApplicationsMatcherService()
return _appl_match_service
|