~wolfgang-groiss/unity-im-lens/trunk

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
#! /usr/bin/python

import sys
from gi.repository import GLib, GObject, Gio
from gi.repository import Dee
_m = dir(Dee.SequenceModel)
from gi.repository import Unity

import dbus

#
# The primary bus name we grab *must* match what we specify in our .lens file
#
BUS_NAME = "net.launchpad.PidginLens"

# These category ids must match the order in which we add them to the lens
CATEGORY_ONLINE = 0
CATEGORY_OFFLINE = 1

class Daemon:

	def __init__ (self):
		# The path for the Lens *must* also match the one in our .lens file
		self._lens = Unity.Lens.new ("/net/launchpad/PidginLens/lens", "pidgin")
		self._pidgin_scope = Unity.Scope.new ("/net/launchpad/PidginLens/scope/pidgin")
		#self._telepathy_scope = Unity.Scope.new ("/net/launchpad/PidginLens/scope/telepathy")
		
		self._lens.props.search_hint = "Type something!"
		self._lens.props.visible = True;
		self._lens.props.search_in_global = True;

		# connect to pidgin
		self.connect_to_pidgin()
		self.update_categories()
		
		# Populate filters
	    filters = []
        f = Unity.RadioOptionFilter.new ("transform",
		                                 "Input Transformation",
		                                 Gio.ThemedIcon.new("input-keyboard-symbolic"),
		                                 False)
	    f.add_option ("online", "Online", None)
        f.add_option ("offline", "Offline Buddies", None)
	    filters.append (f)
        self._lens.props.filters = filters
		
		# Listen for changes and requests
	    self._pidgin_scope.connect ("notify::active-search", self._pidgin_on_search_changed)
        self._pidgin_scope.connect ("notify::active-global-search", self._pidgin_on_global_search_changed)
	    self._pidgin_scope.connect ("activate-uri", self._pidgin_on_uri_activated)
		
        self._lens.add_local_scope (self._pidgin_scope);
	    self._lens.export ();

    	def connect_to_pidgin (self):
		bus = dbus.SessionBus()
		obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
		self._purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
		
	def update_categories (self):
        cats = []
		catids = {}
	    root = self._purple.PurpleBlistGetRoot()
		self.handle_subnodes(root, cats, catids, 0)

		self._lens.props.categories = cats
		self._catids = catids


	def handle_node(self, node, cats, catids, idx):
		#print "hn %i %s %s" % (node, self._purple.PurpleGroupGetName(node),  self._purple.PurpleBlistNodeGetType(node)) #TODO: find out what the missing type is (we have a group "Arbeit" but are missing group "Skype", which is apparently not a group at all
		if node == 0:
			return

		if self._purple.PurpleBlistNodeIsGroup(node):
			name = self._purple.PurpleGroupGetName(node)
	       	cats.append (Unity.Category.new (name,
		                     Gio.ThemedIcon.new("keyboard"),  #TODO
		                     Unity.CategoryRenderer.VERTICAL_TILE))
			catids[str(name)] = idx
			print "catids %s %s" % (name, catids)
			++idx
			
		self.handle_subnodes(node, cats, catids, idx)

	def handle_subnodes(self, node, cats, catids, idx): 
		next = self._purple.PurpleBlistNodeNext(node, True)
		self.handle_node(next, cats, catids, idx)
		
	
	def get_search_string (self, scope):
		search = scope.props.active_search
		return search.props.search_string if search else None
	
	def get_global_search_string (self, scope):
		search = scope.props.active_global_search
		return search.props.search_string if search else None
	
	def search_finished (self, scope):
		search = scope.props.active_search
		if search:
			search.emit("finished")
	
	def global_search_finished (self, scope):
		search = scope.props.active_global_search
		if search:
			search.emit("finished")
	
	def _pidgin_on_search_changed (self, scope, param_spec):		
		search = self.get_search_string(scope)
		results = scope.props.results_model

		accounts = self._purple.PurpleAccountsGetAllActive()
		sl = search.lower()
		
		found=set()
		for account in accounts:
			buddies = self._purple.PurpleFindBuddies(account, "")
			for buddy in buddies:
				if sl in self._purple.PurpleBuddyGetAlias(buddy).lower():
					found.add(buddy)
					
		self._pidgin_update_results_model (search, results, found)
		self.search_finished(scope)
	
	def _pidgin_on_global_search_changed (self, scope, param_spec):
		self._on_search_changed(scope, param_spec)
		
	def _pidgin_update_results_model (self, search, model, buddies):
		model.clear ()
		for buddy in buddies:
			if self._purple.PurpleBuddyIsOnline(buddy):
				cat = CATEGORY_ONLINE
				icon_hint = Gio.ThemedIcon.new ("keyboard").to_string()
			else:
				cat = CATEGORY_OFFLINE
				icon_hint = Gio.ThemedIcon.new ("keyboard").to_string()
		
			icon = self._purple.PurpleBuddyGetIcon(buddy)
			
			if icon != 0:
				icon_hint = self._purple.PurpleBuddyIconGetFullPath(icon)
			else:
				icon_hint = Gio.ThemedIcon.new ("pidgin").to_string()
			
			group=self._purple.PurpleBuddyGetGroup(buddy)
			groupname = self._purple.PurpleGroupGetName(group)
			category = self._catids.get(str(groupname),0)
	
			uri = "pidgin-lens://pidgin-lens-daemon/buddy/%i" % buddy

#			print "buddy %s, group %i, groupname %s, category %i" % (buddy, group, groupname, category)

#			print "%s" % self._catids
			model.append (uri,                                         # uri
			              icon_hint,                                   # string formatted GIcon
			              category,					   # numeric category id
			              "application/x-pidgin-lens-daemon-buddy",    # mimetype
			              self._purple.PurpleBuddyGetAlias(buddy),     # display name
			              "See Wikipedia article about '%i'" % buddy,  # comment
			              "")                                          # FIXME WHATSTHIS?


	def _pidgin_on_uri_activated (self, scope, uri):
		buddy = int(uri.rpartition("/")[2])
		account = self._purple.PurpleBuddyGetAccount(buddy)
		conversation = self._purple.PurpleConversationNew(1, account, self._purple.PurpleBuddyGetName(buddy))
		self._purple.PurpleConversationPresent(conversation)

		self._purple.PurpleConvPresentError(self._purple.PurpleBudddyGetName(buddy), account, "")


		return Unity.ActivationResponse.new(Unity.HandledType.HIDE_DASH, "")
		
if __name__ == "__main__":
	print "main"
	# NOTE: If we used the normal 'dbus' module for Python we'll get
	#       slightly odd results because it uses a default connection
	#       to the session bus that is different from the default connection
	#       GDBus (hence libunity) will use. Meaning that the daemon name
	#       will be owned by a connection different from the one all our
	#       Dee + Unity magic is working on...
	#       Still waiting for nice GDBus bindings to land:
	#                        http://www.piware.de/2011/01/na-zdravi-pygi/
	
	session_bus_connection = Gio.bus_get_sync (Gio.BusType.SESSION, None)
	session_bus = Gio.DBusProxy.new_sync (session_bus_connection, 0, None,
	                                      'org.freedesktop.DBus',
	                                      '/org/freedesktop/DBus',
	                                      'org.freedesktop.DBus', None)
	result = session_bus.call_sync('RequestName',
	                               GLib.Variant ("(su)", (BUS_NAME, 0x4)),
	                               0, -1, None)
	                               
	# Unpack variant response with signature "(u)". 1 means we got it.
	result = result.unpack()[0]
	
	if result != 1 :
		print >> sys.stderr, "Failed to own name %s. Bailing out." % BUS_NAME
		raise SystemExit (1)
	
	daemon = Daemon()
	GObject.MainLoop().run()