Debian Codegraph @

Xpjproject/pjsip-apps/src/pygui/application.py

raw symbols SCIP
1 #
2 # pjsua Python GUI Demo
3 #
4 # Copyright (C)2013 Teluu Inc. (http://www.teluu.com)
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #
20 import sys
21 if sys.version_info[0] >= 3: # Python 3
22 import tkinter as tk
23 from tkinter import ttk
24 from tkinter import messagebox as msgbox
25 else:
26 import Tkinter as tk
27 import tkMessageBox as msgbox
28 import ttk
29
30 import pjsua2 as pj
31 import log
32 import accountsetting
33 import account
34 import buddy
35 import endpoint
36 import settings
37
38 import os
39 import traceback
40
41 # You may try to enable pjsua worker thread by setting USE_THREADS below to True *and*
42 # recreate the swig module with adding -threads option to swig (uncomment USE_THREADS
43 # in swig/python/Makefile). In my experiment this would crash Python as reported in:
44 # http://lists.pjsip.org/pipermail/pjsip_lists.pjsip.org/2014-March/017223.html
45 USE_THREADS = False
46
47 write=sys.stdout.write
48
49 class Application(ttk.Frame):
50 """
51 The Application main frame.
52 """
53 def __init__(self):
54 global USE_THREADS
55 ttk.Frame.__init__(self, name='application', width=300, height=500)
56 self.pack(expand='yes', fill='both')
57 self.master.title('pjsua2 Demo')
58 self.master.geometry('500x500+100+100')
59
60 # Logger
61 self.logger = log.Logger()
62
63 # Accounts
64 self.accList = []
65
66 # GUI variables
67 self.showLogWindow = tk.IntVar(value=0)
68 self.quitting = False
69
70 # Construct GUI
71 self._createWidgets()
72
73 # Log window
74 self.logWindow = log.LogWindow(self)
75 self._onMenuShowHideLogWindow()
76
77 # Instantiate endpoint
78 self.ep = endpoint.Endpoint()
79 self.ep.libCreate()
80
81 # Default config
82 self.appConfig = settings.AppConfig()
83 if USE_THREADS:
84 self.appConfig.epConfig.uaConfig.threadCnt = 1
85 self.appConfig.epConfig.uaConfig.mainThreadOnly = False
86 else:
87 self.appConfig.epConfig.uaConfig.threadCnt = 0
88 self.appConfig.epConfig.uaConfig.mainThreadOnly = True
89 self.appConfig.epConfig.logConfig.writer = self.logger
90 self.appConfig.epConfig.logConfig.filename = "pygui.log"
91 self.appConfig.epConfig.logConfig.fileFlags = pj.PJ_O_APPEND
92 self.appConfig.epConfig.logConfig.level = 5
93 self.appConfig.epConfig.logConfig.consoleLevel = 5
94
95 def saveConfig(self, filename='pygui.js'):
96 # Save disabled accounts since they are not listed in self.accList
97 disabled_accs = [ac for ac in self.appConfig.accounts if not ac.enabled]
98 self.appConfig.accounts = []
99
100 # Get account configs from active accounts
101 for acc in self.accList:
102 acfg = settings.AccConfig()
103 acfg.enabled = True
104 acfg.config = acc.cfg
105 for bud in acc.buddyList:
106 acfg.buddyConfigs.append(bud.cfg)
107 self.appConfig.accounts.append(acfg)
108
109 # Put back disabled accounts
110 self.appConfig.accounts.extend(disabled_accs)
111 # Save
112 self.appConfig.saveFile(filename)
113
114 def start(self, cfg_file='pygui.js'):
115 global USE_THREADS
116 # Load config
117 if cfg_file and os.path.exists(cfg_file):
118 self.appConfig.loadFile(cfg_file)
119
120 if USE_THREADS:
121 self.appConfig.epConfig.uaConfig.threadCnt = 1
122 self.appConfig.epConfig.uaConfig.mainThreadOnly = False
123 else:
124 self.appConfig.epConfig.uaConfig.threadCnt = 0
125 self.appConfig.epConfig.uaConfig.mainThreadOnly = True
126 self.appConfig.epConfig.uaConfig.threadCnt = 0
127 self.appConfig.epConfig.uaConfig.mainThreadOnly = True
128 self.appConfig.epConfig.logConfig.writer = self.logger
129 self.appConfig.epConfig.logConfig.level = 5
130 self.appConfig.epConfig.logConfig.consoleLevel = 5
131
132 # Initialize library
133 self.appConfig.epConfig.uaConfig.userAgent = "pygui-" + self.ep.libVersion().full;
134 self.ep.libInit(self.appConfig.epConfig)
135 self.master.title('pjsua2 Demo version ' + self.ep.libVersion().full)
136
137 # Create transports
138 if self.appConfig.udp.enabled:
139 self.ep.transportCreate(self.appConfig.udp.type, self.appConfig.udp.config)
140 if self.appConfig.tcp.enabled:
141 self.ep.transportCreate(self.appConfig.tcp.type, self.appConfig.tcp.config)
142 if self.appConfig.tls.enabled:
143 self.ep.transportCreate(self.appConfig.tls.type, self.appConfig.tls.config)
144
145 # Add accounts
146 for cfg in self.appConfig.accounts:
147 if cfg.enabled:
148 self._createAcc(cfg.config)
149 acc = self.accList[-1]
150 for buddy_cfg in cfg.buddyConfigs:
151 self._createBuddy(acc, buddy_cfg)
152
153 # Start library
154 self.ep.libStart()
155
156 # Start polling
157 if not USE_THREADS:
158 self._onTimer()
159
160 def updateAccount(self, acc):
161 if acc.deleting:
162 return # ignore
163 iid = str(acc.randId)
164 text = acc.cfg.idUri
165 status = acc.statusText()
166
167 values = (status,)
168 if self.tv.exists(iid):
169 self.tv.item(iid, text=text, values=values)
170 else:
171 self.tv.insert('', 'end', iid, open=True, text=text, values=values)
172
173 def updateBuddy(self, bud):
174 iid = 'buddy' + str(bud.randId)
175 text = bud.cfg.uri
176 status = bud.statusText()
177
178 values = (status,)
179 if self.tv.exists(iid):
180 self.tv.item(iid, text=text, values=values)
181 else:
182 self.tv.insert(str(bud.account.randId), 'end', iid, open=True, text=text, values=values)
183
184 def _createAcc(self, acc_cfg):
185 acc = account.Account(self)
186 acc.cfg = acc_cfg
187 self.accList.append(acc)
188 self.updateAccount(acc)
189 acc.create(acc.cfg)
190 acc.cfgChanged = False
191 self.updateAccount(acc)
192
193 def _createBuddy(self, acc, buddy_cfg):
194 bud = buddy.Buddy(self)
195 bud.cfg = buddy_cfg
196 bud.account = acc
197 bud.create(acc, bud.cfg)
198 self.updateBuddy(bud)
199 acc.buddyList.append(bud)
200
201 def _createWidgets(self):
202 self._createAppMenu()
203
204 # Main pane, a Treeview
205 self.tv = ttk.Treeview(self, columns=('Status'), show='tree')
206 self.tv.pack(side='top', fill='both', expand='yes', padx=5, pady=5)
207
208 self._createContextMenu()
209
210 # Handle close event
211 self.master.protocol("WM_DELETE_WINDOW", self._onClose)
212
213 def _createAppMenu(self):
214 # Main menu bar
215 top = self.winfo_toplevel()
216 self.menubar = tk.Menu()
217 top.configure(menu=self.menubar)
218
219 # File menu
220 file_menu = tk.Menu(self.menubar, tearoff=False)
221 self.menubar.add_cascade(label="File", menu=file_menu)
222 file_menu.add_command(label="Add account..", command=self._onMenuAddAccount)
223 file_menu.add_checkbutton(label="Show/hide log window", command=self._onMenuShowHideLogWindow, variable=self.showLogWindow)
224 file_menu.add_separator()
225 file_menu.add_command(label="Settings...", command=self._onMenuSettings)
226 file_menu.add_command(label="Save Settings", command=self._onMenuSaveSettings)
227 file_menu.add_separator()
228 file_menu.add_command(label="Quit", command=self._onMenuQuit)
229
230 # Window menu
231 self.window_menu = tk.Menu(self.menubar, tearoff=False)
232 self.menubar.add_cascade(label="Window", menu=self.window_menu)
233
234 # Help menu
235 help_menu = tk.Menu(self.menubar, tearoff=False)
236 self.menubar.add_cascade(label="Help", menu=help_menu)
237 help_menu.add_command(label="About", underline=2, command=self._onMenuAbout)
238
239 def _showChatWindow(self, chat_inst):
240 chat_inst.showWindow()
241
242 def updateWindowMenu(self):
243 # Chat windows
244 self.window_menu.delete(0, tk.END)
245 for acc in self.accList:
246 for c in acc.chatList:
247 cmd = lambda arg=c: self._showChatWindow(arg)
248 self.window_menu.add_command(label=c.title, command=cmd)
249
250 def _createContextMenu(self):
251 top = self.winfo_toplevel()
252
253 # Create Account context menu
254 self.accMenu = tk.Menu(top, tearoff=False)
255 # Labels, must match with _onAccContextMenu()
256 labels = ['Unregister', 'Reregister', 'Add buddy...', '-',
257 'Online', 'Invisible', 'Away', 'Busy', '-',
258 'Settings...', '-',
259 'Delete...']
260 for label in labels:
261 if label=='-':
262 self.accMenu.add_separator()
263 else:
264 cmd = lambda arg=label: self._onAccContextMenu(arg)
265 self.accMenu.add_command(label=label, command=cmd)
266
267 # Create Buddy context menu
268 # Labels, must match with _onBuddyContextMenu()
269 self.buddyMenu = tk.Menu(top, tearoff=False)
270 labels = ['Audio call', 'Send instant message', '-',
271 'Subscribe', 'Unsubscribe', '-',
272 'Settings...', '-',
273 'Delete...']
274
275 for label in labels:
276 if label=='-':
277 self.buddyMenu.add_separator()
278 else:
279 cmd = lambda arg=label: self._onBuddyContextMenu(arg)
280 self.buddyMenu.add_command(label=label, command=cmd)
281
282 if (top.tk.call('tk', 'windowingsystem')=='aqua'):
283 self.tv.bind('<2>', self._onTvRightClick)
284 self.tv.bind('<Control-1>', self._onTvRightClick)
285 else:
286 self.tv.bind('<3>', self._onTvRightClick)
287 self.tv.bind('<Double-Button-1>', self._onTvDoubleClick)
288
289 def _getSelectedAccount(self):
290 items = self.tv.selection()
291 if not items:
292 return None
293 try:
294 iid = int(items[0])
295 except:
296 return None
297 accs = [acc for acc in self.accList if acc.randId==iid]
298 if not accs:
299 return None
300 return accs[0]
301
302 def _getSelectedBuddy(self):
303 items = self.tv.selection()
304 if not items:
305 return None
306 try:
307 iid = int(items[0][5:])
308 iid_parent = int(self.tv.parent(items[0]))
309 except:
310 return None
311
312 accs = [acc for acc in self.accList if acc.randId==iid_parent]
313 if not accs:
314 return None
315
316 buds = [b for b in accs[0].buddyList if b.randId==iid]
317 if not buds:
318 return None
319
320 return buds[0]
321
322 def _onTvRightClick(self, event):
323 iid = self.tv.identify_row(event.y)
324 #iid = self.tv.identify('item', event.x, event.y)
325 if iid:
326 self.tv.selection_set( (iid,) )
327 acc = self._getSelectedAccount()
328 if acc:
329 self.accMenu.post(event.x_root, event.y_root)
330 else:
331 # A buddy is selected
332 self.buddyMenu.post(event.x_root, event.y_root)
333
334 def _onTvDoubleClick(self, event):
335 iid = self.tv.identify_row(event.y)
336 if iid:
337 self.tv.selection_set( (iid,) )
338 acc = self._getSelectedAccount()
339 if acc:
340 self.cfgChanged = False
341 dlg = accountsetting.Dialog(self.master, acc.cfg)
342 if dlg.doModal():
343 self.updateAccount(acc)
344 acc.modify(acc.cfg)
345 else:
346 bud = self._getSelectedBuddy()
347 acc = bud.account
348 chat = acc.findChat(bud.cfg.uri)
349 if not chat:
350 chat = acc.newChat(bud.cfg.uri)
351 chat.showWindow()
352
353 def _onAccContextMenu(self, label):
354 acc = self._getSelectedAccount()
355 if not acc:
356 return
357
358 if label=='Unregister':
359 acc.setRegistration(False)
360 elif label=='Reregister':
361 acc.setRegistration(True)
362 elif label=='Online':
363 ps = pj.PresenceStatus()
364 ps.status = pj.PJSUA_BUDDY_STATUS_ONLINE
365 acc.setOnlineStatus(ps)
366 elif label=='Invisible':
367 ps = pj.PresenceStatus()
368 ps.status = pj.PJSUA_BUDDY_STATUS_OFFLINE
369 acc.setOnlineStatus(ps)
370 elif label=='Away':
371 ps = pj.PresenceStatus()
372 ps.status = pj.PJSUA_BUDDY_STATUS_ONLINE
373 ps.activity = pj.PJRPID_ACTIVITY_AWAY
374 ps.note = "Away"
375 acc.setOnlineStatus(ps)
376 elif label=='Busy':
377 ps = pj.PresenceStatus()
378 ps.status = pj.PJSUA_BUDDY_STATUS_ONLINE
379 ps.activity = pj.PJRPID_ACTIVITY_BUSY
380 ps.note = "Busy"
381 acc.setOnlineStatus(ps)
382 elif label=='Settings...':
383 self.cfgChanged = False
384 dlg = accountsetting.Dialog(self.master, acc.cfg)
385 if dlg.doModal():
386 self.updateAccount(acc)
387 acc.modify(acc.cfg)
388 elif label=='Delete...':
389 msg = "Do you really want to delete account '%s'?" % acc.cfg.idUri
390 if msgbox.askquestion('Delete account?', msg, default=msgbox.NO) != u'yes':
391 return
392 iid = str(acc.randId)
393 self.accList.remove(acc)
394 acc.setRegistration(False)
395 acc.deleting = True
396 del acc
397 self.tv.delete( (iid,) )
398 elif label=='Add buddy...':
399 cfg = pj.BuddyConfig()
400 dlg = buddy.SettingDialog(self.master, cfg)
401 if dlg.doModal():
402 self._createBuddy(acc, cfg)
403 else:
404 assert not ("Unknown menu " + label)
405
406 def _onBuddyContextMenu(self, label):
407 bud = self._getSelectedBuddy()
408 if not bud:
409 return
410 acc = bud.account
411
412 if label=='Audio call':
413 chat = acc.findChat(bud.cfg.uri)
414 if not chat: chat = acc.newChat(bud.cfg.uri)
415 chat.showWindow()
416 chat.startCall()
417 elif label=='Send instant message':
418 chat = acc.findChat(bud.cfg.uri)
419 if not chat: chat = acc.newChat(bud.cfg.uri)
420 chat.showWindow(True)
421 elif label=='Subscribe':
422 bud.subscribePresence(True)
423 elif label=='Unsubscribe':
424 bud.subscribePresence(False)
425 elif label=='Settings...':
426 subs = bud.cfg.subscribe
427 uri = bud.cfg.uri
428 dlg = buddy.SettingDialog(self.master, bud.cfg)
429 if dlg.doModal():
430 self.updateBuddy(bud)
431 # URI updated?
432 if uri != bud.cfg.uri:
433 cfg = bud.cfg
434 # del old
435 iid = 'buddy' + str(bud.randId)
436 acc.buddyList.remove(bud)
437 del bud
438 self.tv.delete( (iid,) )
439 # add new
440 self._createBuddy(acc, cfg)
441 # presence subscribe setting updated
442 elif subs != bud.cfg.subscribe:
443 bud.subscribePresence(bud.cfg.subscribe)
444 elif label=='Delete...':
445 msg = "Do you really want to delete buddy '%s'?" % bud.cfg.uri
446 if msgbox.askquestion('Delete buddy?', msg, default=msgbox.NO) != u'yes':
447 return
448 iid = 'buddy' + str(bud.randId)
449 acc.buddyList.remove(bud)
450 del bud
451 self.tv.delete( (iid,) )
452 else:
453 assert not ("Unknown menu " + label)
454
455 def _onTimer(self):
456 if not self.quitting:
457 self.ep.libHandleEvents(10)
458 if not self.quitting:
459 self.master.after(50, self._onTimer)
460
461 def _onClose(self):
462 self.saveConfig()
463 self.quitting = True
464 self.ep.libDestroy()
465 self.ep = None
466 self.update()
467 self.quit()
468
469 def _onMenuAddAccount(self):
470 cfg = pj.AccountConfig()
471 dlg = accountsetting.Dialog(self.master, cfg)
472 if dlg.doModal():
473 self._createAcc(cfg)
474
475 def _onMenuShowHideLogWindow(self):
476 if self.showLogWindow.get():
477 self.logWindow.deiconify()
478 else:
479 self.logWindow.withdraw()
480
481 def _onMenuSettings(self):
482 dlg = settings.Dialog(self, self.appConfig)
483 if dlg.doModal():
484 msgbox.showinfo(self.master.title(), 'You need to restart for new settings to take effect')
485
486 def _onMenuSaveSettings(self):
487 self.saveConfig()
488
489 def _onMenuQuit(self):
490 self._onClose()
491
492 def _onMenuAbout(self):
493 msgbox.showinfo(self.master.title(), 'About')
494
495
496 class ExceptionCatcher:
497 """Custom Tk exception catcher, mainly to display more information
498 from pj.Error exception
499 """
500 def __init__(self, func, subst, widget):
501 self.func = func
502 self.subst = subst
503 self.widget = widget
504 def __call__(self, *args):
505 try:
506 if self.subst:
507 args = apply(self.subst, args)
508 return apply(self.func, args)
509 except pj.Error as error:
510 write("Exception:\r\n")
511 write(" ," + error.info() + "\r\n")
512 write("Traceback:\r\n")
513 write(traceback.print_stack())
514 log.writeLog2(1, 'Exception: ' + error.info() + '\n')
515 except Exception as error:
516 write("Exception:\r\n")
517 write(" ," + str(error) + "\r\n")
518 write("Traceback:\r\n")
519 write(traceback.print_stack())
520 log.writeLog2(1, 'Exception: ' + str(error) + '\n')
521
522 def main():
523 #tk.CallWrapper = ExceptionCatcher
524 app = Application()
525 app.start()
526 app.mainloop()
527
528 if __name__ == '__main__':
529 main()