File: main.py.in

package info (click to toggle)
sushi 1.4.0+git20160822+dfsg-4.1
  • links: PTS
  • area: main
  • in suites: buster, sid
  • size: 3,860 kB
  • sloc: python: 26,550; ansic: 8,617; xml: 516; makefile: 59; sh: 43
file content (739 lines) | stat: -rwxr-xr-x 17,750 bytes parent folder | download | duplicates (2)
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
#!/usr/bin/env python
# coding: UTF-8
"""
Copyright (c) 2009 Marian Tietz
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
"""

import os
import sys
import traceback

import glib
from gi.repository import GObject

try:
	import urwid
except ImportError, e:
	print >> sys.stderr, "Failed to import urwid: %s" % (e)
	print >> sys.stderr, "Do you have urwid installed?"
	sys.exit(1)

from urwid import MetaSignals

try:
	from gi.repository import GObject
except ImportError:
	print >> sys.stderr, "You need python-gobject installed."
	sys.exit(1)
import re

import logging
import locale

try:
	import gettext
	from gettext import gettext as _
except ImportError:
	print >> sys.stderr, "You need gettext installed."
	sys.exit(1)

import config
import messages
import commands
import connection
import signals
import tabs
import plugin_control

from typecheck import types

import extends
from extends import *
from input_history import InputHistory

from helper import tabcompletion

"""
 -------context-------
| --inner context---- |
|| HEADER            ||
||                   ||
|| BODY              ||
||                   ||
|| DIVIDER           ||
| ------------------- |
| FOOTER              |
 ---------------------

inner context = context.body
context.body.body = BODY
context.body.header = HEADER
context.body.footer = DIVIDER
context.footer = FOOTER

HEADER = Notice line (urwid.Text)
BODY = Extended ListBox
DIVIDER = Divider with information (urwid.Text)
FOOTER = Input line (Ext. Edit)
"""

NIGIRI_VERSION = "@SUSHI_VERSION@"

class MainWindow(object):

	__metaclass__ = MetaSignals
	signals = ["quit","keypress","tab_switched"]

	_palette = [
			('divider','black','dark cyan', 'standout'),
			('text','light gray', 'default'),
			('bold_text', 'light gray', 'default', 'bold'),
			("body", "text"),
			("footer", "text"),
			("header", "text"),
		]

	for type, bg in (
			("div_fg_", "dark cyan"),
			("", "default")):
		for name, color in (
				("red","dark red"),
				("blue", "dark blue"),
				("green", "dark green"),
				("yellow", "yellow"),
				("magenta", "dark magenta"),
				("gray", "light gray"),
				("white", "white"),
				("black", "black")):
			_palette.append( (type + name, color, bg) )


	def __init__(self):
		self.current_tab = None
		self.servers = []
		self.shortcut_pattern = re.compile(
			config.get("nigiri", "shortcut_pattern"))
		self.shall_quit = False

	def main(self):
		""" entry point to start UI """

		self.ui = urwid.raw_display.Screen ()
		self.ui.register_palette (self._palette)

		self.build_interface()

		self.update_divider()

		self.generic_input_history = InputHistory(
				text_callback = self.footer.get_edit_text)


		self.ui.run_wrapper(self.run)

	def run(self):
		""" setup input handler, invalidate handler to
			automatically redraw the interface if needed.

			connect to dbus, start mainloop.
		"""

		def input_cb(key):
			if self.shall_quit:
				raise urwid.ExitMainLoop
			self.keypress(self.size, key)

		self.size = self.ui.get_cols_rows()

		self.main_loop = urwid.MainLoop(
				self.context,
				screen=self.ui,
				handle_mouse=False,
				unhandled_input=input_cb,
				event_loop=urwid.GLibEventLoop()
			)

		connection.connect()

		def call_redraw(*x):
			self.draw_interface()
			invalidate.locked = False
			return True

		inv = urwid.canvas.CanvasCache.invalidate

		def invalidate (cls, *a, **k):
			inv(*a, **k)

			if not invalidate.locked:
				invalidate.locked = True
				self.main_loop.set_alarm_in(0, call_redraw)

		invalidate.locked = False
		urwid.canvas.CanvasCache.invalidate = classmethod(invalidate)

		try:
			self.main_loop.run()
		except KeyboardInterrupt:
			self.quit()

	def quit(self, exit=True):
		""" stops the ui, exits the application (if exit=True)
			After the UI is stopped, the config is written.
		"""
		urwid.emit_signal(self, "quit")

		config.write_config_file ()

		self.shall_quit = True

		if exit:
			sys.exit(0)

	def _create_widgets(self):
		""" create the UI widgets """
		self.header = urwid.Text("nigiri %s" % NIGIRI_VERSION)
		self.footer = extends.Edit.ExtendedEdit("> ")
		self.divider = urwid.Text("Initializing.")

		self.generic_output_walker = urwid.SimpleListWalker([])
		self.body = extends.ListBox.ExtendedListBox(
			self.generic_output_walker)

		urwid.connect_signal(self.body, "set_auto_scroll",
			self.handle_body_auto_scroll)

	def _setup_widgets(self):
		""" set coloring and attributes of the UI widgets
			created in _create_widgets
		"""
		self.header = urwid.AttrWrap (self.header, "divider")
		self.footer = urwid.AttrWrap (self.footer, "footer")
		self.divider = urwid.AttrWrap (self.divider, "divider")
		self.body = urwid.AttrWrap (self.body, "body")

		# apply config values
		if not config.get_bool ("nigiri", "wrap_input"):
			self.footer.set_wrap_mode ("clip")
		else:
			self.footer.set_wrap_mode ("space")

	def _setup_context(self):
		""" wrap a Frame called context around the widgets
			created in _create_widgets
		"""
		self.context = urwid.Frame (self.body, header = self.header,
				footer = self.divider)
		self.context = urwid.Frame (self.context, footer = self.footer)

		self.context.set_focus ("footer")

	def build_interface(self):
		""" call the widget methods to build the UI """
		self._create_widgets()
		self._setup_widgets()
		self._setup_context()

	def draw_interface(self):
		self.main_loop.draw_screen()

	def keypress(self, size, key):
		""" handle keypress events """

		urwid.emit_signal(self, "keypress", size, key)

		if key != "tab":
			tabcompletion.stopIteration()

		if key in ("page up","page down"):
			self.body.keypress (size, key)

		elif key == "window resize":
			self.size = self.ui.get_cols_rows()

		elif key == "enter":
			# Parse data or (if parse failed)
			# send it to the current world
			input = self.footer.get_edit_text()

			self.footer.set_edit_text(" "*len(input))
			self.footer.set_edit_text("")

			if not commands.parse (self, input):
				# no parsable command, send text
				if self.current_tab:
					commands.send_text(self.current_tab, input)

			if self.current_tab:
				history = self.current_tab.input_history
			else:
				history = self.generic_input_history

			history.add_entry (input)
			history.reset()

		elif key == "up":
			history = self.generic_input_history

			if self.current_tab:
				history = self.current_tab.input_history

			prev = history.get_previous()

			if prev == None:
				return

			self.footer.edit_pos = None
			self.footer.set_edit_text (prev)
			self.footer.set_edit_pos (len(prev))

		elif key == "down":
			history = self.generic_input_history

			if self.current_tab:
				history = self.current_tab.input_history

			next = history.get_next()

			if next == None:
				return

			self.footer.set_edit_text (next)
			self.footer.set_edit_pos (len(next))

		elif key == "ctrl p":
			self.switch_to_previous_tab()

		elif key == "ctrl n":
			self.switch_to_next_tab()

		elif self.shortcut_pattern.match(key):
			self.switch_to_tabid(int(key[-1]))

		elif key == "ctrl u":
			# clear the edit line
			self.footer.set_edit_text ("")
			self.footer.set_edit_pos (0)

		elif key == "ctrl w":
			# remove the text from cursor
			# position to previous space

			def ctrlw(et, ep):
				i = et[:ep].rfind(" ")
				if i == -1:
					et = et[ep:]
				else:
					et = et[:i+1] + et[ep:]
				return et

			# FIXME: fix position setting
			new = ctrlw(
				self.footer.get_edit_text(),
				self.footer.edit_pos)
			self.footer.set_edit_text(new)

		elif key == "tab":
			logging.debug("tab is pressed!")
			tabcompletion.complete(self.footer, self.footer.get_edit_text())

		else:
			self.context.keypress (size, key)

	def find_server(self, server_name):
		try:
			i = [n.name.lower()
				for n in self.servers].index(server_name.lower())
		except ValueError:
			return None
		else:
			return self.servers[i]

	def find_tab(self, parent_name, child_name = ""):
		try:
			i = [n.name.lower()
				for n in self.servers].index(parent_name.lower())
		except ValueError:
			return None
		else:
			if not child_name:
				return self.servers[i]
			else:
				try:
					j = [n.name.lower()
						for n in self.servers[i].children].index(
							child_name.lower())
				except ValueError:
					return None
				else:
					return self.servers[i].children[j]
		return None

	def add_server(self, server_tab):
		self.servers.append(server_tab)

		server_tab.support_chantypes = connection.sushi.support_chantypes(
			server_tab.name)

		urwid.connect_signal(server_tab, "remove",
			self.handle_server_remove)
		urwid.connect_signal(server_tab, "child_added",
			self.handle_channel_add)
		urwid.connect_signal(server_tab, "child_removed",
			self.handle_channel_remove)

		server_tab.input_history = InputHistory(
			text_callback = self.footer.get_edit_text)

		self.update_divider()

	def remove_server(self, server):
		try:
			i = self.servers.index(server)
		except ValueError:
			return
		else:
			del self.servers[i]
			self.update_divider()

	@types(id = int)
	def switch_to_tabid(self, id):
		""" Switch to the _visible_ number of the tab. """

		tablist = tabs.tree_to_list(self.servers)
		if not config.get_bool("nigiri","server_shortcuts"):
			tablist = [n for n in tablist if type(n) != tabs.Server]
		try:
			tab = tablist[id-1]
		except IndexError:
			return
		self.switch_to_tab(tab)

	def switch_to_tab(self, tab):
		""" switch to the given tab and emit tab_switched signal
			if switching is done
		"""

		if self.current_tab:
			# set readline and save typed text from input bar
			self.current_tab.set_readline()
			self.current_tab.input_text = self.footer.get_edit_text()

		self.current_tab = tab

		if not tab:
			self.body.switch_body(self.generic_output_walker)

		else:
			# Set body content to tab content
			self.body.switch_body(tab.output_walker)
			tab.reset_status()

			if type(tab) == tabs.Channel:
				self.header.set_text(tab.get_topic())
			else:
				self.header.set_text("")

			# Restore typed text in the input bar
			self.footer.set_edit_text(tab.input_text)
			self.footer.set_edit_pos(len(tab.input_text))

		if tab.auto_scroll:
			self.body.scroll_to_bottom()
		self.update_divider()

		urwid.emit_signal(self, "tab_switched", tab)

	def switch_to_next_tab (self):
		tablist = tabs.tree_to_list(self.servers)

		try:
			current_index = tablist.index (self.current_tab)
		except ValueError:
			if tablist:
				self.switch_to_tab(tablist[0])
			return

		if (current_index + 1) >= len (tablist):
			current_index = 0
		else:
			current_index += 1

		self.switch_to_tab (tablist[current_index])

	def switch_to_previous_tab (self):
		tablist = tabs.tree_to_list(self.servers)
		try:
			current_index = tablist.index(self.current_tab)
		except ValueError:
			if tablist:
				self.switch_to_tab(tablist[0])
			return

		self.switch_to_tab (tablist[current_index - 1])


	# TODO:  update_divider without color usage
	# TODO:: for people who can't see colors

	def nc_update_divider(self):
		pass

	def update_divider(self):
		"""
		0: [maki] green or red highlighted
		1: "Not connected." or tab id
		if no connection: abort here.
		2: tab name
		3: status of the tab (joined / connected)
		4: tab list with highlights
		"""
		markup = []
		tablist = tabs.tree_to_list(self.servers)

		try:
			tabid = tablist.index(self.current_tab)
		except ValueError:
			tabid = -1

		# [maki]
		markup.append(("divider", "["))
		if connection.sushi.connected:
			markup.append(("div_fg_blue","maki"))
		else:
			markup.append(("div_fg_red","maki"))
		markup.append(("divider", "] "))

		if not self.servers:
			markup.append(("divider", "Not connected to any server."))
			self.divider.set_text(markup)
			return

		else:
			# add <nick>@<server>:<current tab>
			temp = "%(nick)s@%(server)s:%(tab)s (%(id)s) "

			if self.current_tab:
				subdict = {
					"tab":str(self.current_tab),
					"nick":"",
					"server":"",
					"id":""
				}

				if type(self.current_tab) == tabs.Server:
					subdict["nick"] = self.current_tab.get_nick() or "-"
					subdict["server"] = str(self.current_tab)
				else:
					subdict["nick"] = self.current_tab.parent.get_nick() or "-"
					subdict["server"] = str(self.current_tab.parent.name)

				subdict["id"] = str(tabid+1)

				markup.append(("divider", temp % subdict))

			else:
				markup.append(("divider", "-@-:- "))

		# tab status (joined / connected)
		if self.current_tab:
			if type(self.current_tab) == tabs.Channel:
				# check if joined
				if not self.current_tab.connected:
					markup.append(("divider", "(not connected) "))
				elif not self.current_tab.joined:
					markup.append(("divider", "(not joined) "))
			else:
				# check if connected
				if not self.current_tab.connected:
					markup.append(("divider", "(not connected) "))

		# display tabnumbers which are active
		markup.append(("divider", "["))
		active_tabs = [tab for tab in tablist if tab.status and tab != self.current_tab]
		active_tabs_len = len(active_tabs)

		for i in range(active_tabs_len):

			tab = active_tabs[i]
			try:
				name = str(tablist.index(tab)+1)
			except ValueError:
				name = "UNAVAIL"
			color = "divider"

			if tab.has_status("actions") or tab.has_status("actions_own"):
				color = "div_fg_gray"

			if tab.has_status("messages") or tab.has_status("messages_own"):
				color = "div_fg_white"

			if tab.has_status("actions_highlight"):
				color = "div_fg_yellow"

			if tab.has_status("messages_highlight"):
				color = "div_fg_magenta"

			if tab.has_status("informative"):
				color = "div_fg_yellow"


			markup.append((color, name))

			if i+1 != active_tabs_len:
				markup.append(("divider", ","))

		markup.append(("divider", "]"))

		self.divider.set_text(markup)

	@types(text = (str, unicode, list))
	def print_text(self, text):
		"""
		print the given text in the _current_ window
		"""

		if self.current_tab:
			walker = self.current_tab.output_walker

		else:
			walker = self.generic_output_walker

		if text and text[-1] == "\n":
			text = text[:-1]

		walker.append (urwid.Text (text))

		self.body.scroll_to_bottom()

	# Signal handlers

	def handle_body_auto_scroll(self, switch):
		if self.current_tab:
			self.current_tab.auto_scroll = switch

	def handle_server_remove(self, server):
		self.remove_server(server)

	def handle_channel_add(self, server_tab, channel_tab):
		channel_tab.input_history = InputHistory(
			text_callback = self.footer.get_edit_text)
		self.update_divider()

	def handle_channel_remove(self, server_tab, channel_tab):
		if channel_tab == self.current_tab:
			self.switch_to_next_tab()

		if connection.sushi.connected and channel_tab.joined:
			connection.sushi.part(server_tab.name, channel_tab.name, "")

		self.update_divider()

	def handle_maki_disconnect(self):
		self.update_divider()



def except_hook(extype, exobj, extb, manual=False):
	if not manual:
		try:
			main_window.quit(exit=False)
		except NameError:
			pass

	message = _("An error occured:\n%(divider)s\n%(traceback)s\n"\
		"%(exception)s\n%(divider)s" % {
			"divider": 20*"-",
			"traceback": "".join(traceback.format_tb(extb)),
			"exception": extype.__name__+": "+str(exobj)
		})

	logging.error(message)

	if manual:
		messages.print_error(message)
	else:
		print >> sys.stderr, message


def setup_logging():
	""" set the path of the logfile to tekka.logfile config
		value and create it (including path) if needed.
		After that, add a logging handler for exceptions
		which reports exceptions catched by the logger
		to the tekka_excepthook. (DBus uses this)
	"""
	try:
		class ExceptionHandler(logging.Handler):
			""" handler for exceptions caught with logging.error.
				dump those exceptions to the exception handler.
			"""
			def emit(self, record):
				if record.exc_info:
					except_hook(*record.exc_info)

		logfile = config.get("nigiri","logfile")
		logdir = os.path.dirname(logfile)

		if not os.path.exists(logdir):
			os.makedirs(logdir)

		logging.basicConfig(filename=logfile, level=logging.DEBUG,
			filemode="w")

		logging.getLogger("").addHandler(ExceptionHandler())

	except BaseException, e:
		print >> sys.stderr, "Logging init error: %s" % (e)


if __name__ == "__main__":
	global main_window, stderr

	config.setup()

	setup_logging()

	# setup locale stuff
	try:
		locale.setlocale(locale.LC_ALL, "")
	except:
		pass

	gettext.bindtextdomain("nigiri", config.get("nigiri","locale_dir"))
	gettext.textdomain("nigiri")

	main_window = MainWindow()

	sys.excepthook = except_hook

	signals.setup(main_window)

	messages.setup(main_window)

	tabcompletion.setup(main_window)

	main_window.main()