3 # Uzbl tabbing wrapper using a fifo socket interface
4 # Copyright (c) 2009, Tom Adams <tom@holizz.com>
5 # Copyright (c) 2009, Chris van Dijk <cn.vandijk@hotmail.com>
6 # Copyright (c) 2009, Mason Larobina <mason.larobina@gmail.com>
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
23 # Tom Adams <tom@holizz.com>
24 # Wrote the original uzbl_tabbed.py as a proof of concept.
26 # Chris van Dijk (quigybo) <cn.vandijk@hotmail.com>
27 # Made signifigant headway on the old uzbl_tabbing.py script on the
28 # uzbl wiki <http://www.uzbl.org/wiki/uzbl_tabbed>
30 # Mason Larobina <mason.larobina@gmail.com>
31 # Rewrite of the uzbl_tabbing.py script to use a fifo socket interface
32 # and inherit configuration options from the user's uzbl config.
35 # mxey <mxey@ghosthacking.net>
36 # uzbl_config path now honors XDG_CONFIG_HOME if it exists.
40 # Because this version of uzbl_tabbed is able to inherit options from your main
41 # uzbl configuration file you may wish to configure uzbl tabbed from there.
42 # Here is a list of configuration options that can be customised and some
43 # example values for each:
45 # set show_tablist = 1
46 # set show_gtk_tabs = 0
47 # set switch_to_new_tabs = 1
48 # set save_session = 1
49 # set gtk_tab_pos = (left|bottom|top|right)
50 # set max_title_len = 50
51 # set new_tab_title = New tab
52 # set status_background = #303030
53 # set session_file = $HOME/.local/share/session
54 # set tab_colours = foreground = "#999"
55 # set tab_text_colours = foreground = "#444"
56 # set selected_tab = foreground = "#aaa" background="#303030"
57 # set selected_tab_text = foreground = "green"
58 # set window_size = 800,800
60 # And the keybindings:
62 # set bind_new_tab = gn
63 # set bind_tab_from_clip = gY
64 # set bind_close_tab = gC
65 # set bind_next_tab = gt
66 # set bind_prev_tab = gT
67 # set bind_goto_tab = gi_
68 # set bind_goto_first = g<
69 # set bind_goto_last = g>
71 # And uzbl_tabbed.py takes care of the actual binding of the commands via each
72 # instances fifo socket.
76 # - new windows are not caught and opened in a new tab.
77 # - when uzbl_tabbed.py crashes it takes all the children with it.
78 # - when a new tab is opened when using gtk tabs the tab button itself
79 # grabs focus from its child for a few seconds.
80 # - when switch_to_new_tabs is not selected the notebook page is
81 # maintained but the new window grabs focus (try as I might to stop it).
85 # - add command line options to use a different session file, not use a
86 # session file and or open a uri on starup.
87 # - ellipsize individual tab titles when the tab-list becomes over-crowded
88 # - add "<" & ">" arrows to tablist to indicate that only a subset of the
89 # currently open tabs are being displayed on the tablist.
90 # - add the small tab-list display when both gtk tabs and text vim-like
91 # tablist are hidden (I.e. [ 1 2 3 4 5 ])
93 # - pass a uzbl socketid to uzbl_tabbed.py and have it assimilated into
94 # the collective. Resistance is futile!
115 sys.stderr.write("%s\n"%msg)
118 # ============================================================================
119 # ::: Default configuration section ::::::::::::::::::::::::::::::::::::::::::
120 # ============================================================================
122 # Location of your uzbl data directory.
123 if 'XDG_DATA_HOME' in os.environ.keys() and os.environ['XDG_DATA_HOME']:
124 data_dir = os.path.join(os.environ['XDG_DATA_HOME'], 'uzbl/')
126 data_dir = os.path.join(os.environ['HOME'], '.local/share/uzbl/')
127 if not os.path.exists(data_dir):
128 error("Warning: uzbl data_dir does not exist: %r" % data_dir)
130 # Location of your uzbl configuration file.
131 if 'XDG_CONFIG_HOME' in os.environ.keys() and os.environ['XDG_CONFIG_HOME']:
132 uzbl_config = os.path.join(os.environ['XDG_CONFIG_HOME'], 'uzbl/config')
134 uzbl_config = os.path.join(os.environ['HOME'],'.config/uzbl/config')
135 if not os.path.exists(uzbl_config):
136 error("Warning: Cannot locate your uzbl_config file %r" % uzbl_config)
138 # All of these settings can be inherited from your uzbl config file.
141 'show_tablist': True, # Show text uzbl like statusbar tab-list
142 'show_gtk_tabs': False, # Show gtk notebook tabs
143 'tablist_top': True, # Display tab-list at top of window
144 'gtk_tab_pos': 'top', # Gtk tab position (top|left|bottom|right)
145 'switch_to_new_tabs': True, # Upon opening a new tab switch to it
148 'tab_titles': True, # Display tab titles (else only tab-nums)
149 'new_tab_title': 'Loading', # New tab title
150 'max_title_len': 50, # Truncate title at n characters
151 'show_ellipsis': True, # Show ellipsis when truncating titles
154 'save_session': True, # Save session in file when quit
155 'fifo_dir': '/tmp', # Path to look for uzbl fifo
156 'socket_dir': '/tmp', # Path to look for uzbl socket
157 'icon_path': os.path.join(data_dir, 'uzbl.png'),
158 'session_file': os.path.join(data_dir, 'session'),
161 'status_background': "#303030", # Default background for all panels
162 'window_size': "800,800", # width,height in pixels
165 'bind_new_tab': 'gn', # Open new tab.
166 'bind_tab_from_clip': 'gY', # Open tab from clipboard.
167 'bind_tab_from_uri': 'go _', # Open new tab and goto entered uri.
168 'bind_close_tab': 'gC', # Close tab.
169 'bind_next_tab': 'gt', # Next tab.
170 'bind_prev_tab': 'gT', # Prev tab.
171 'bind_goto_tab': 'gi_', # Goto tab by tab-number (in title)
172 'bind_goto_first': 'g<', # Goto first tab
173 'bind_goto_last': 'g>', # Goto last tab
175 # Add custom tab style definitions to be used by the tab colour policy
176 # handler here. Because these are added to the config dictionary like
177 # any other uzbl_tabbed configuration option remember that they can
178 # be superseeded from your main uzbl config file.
179 'tab_colours': 'foreground = "#888" background = "#303030"',
180 'tab_text_colours': 'foreground = "#bbb"',
181 'selected_tab': 'foreground = "#fff"',
182 'selected_tab_text': 'foreground = "green"',
183 'tab_indicate_https': True,
184 'https_colours': 'foreground = "#888"',
185 'https_text_colours': 'foreground = "#9c8e2d"',
186 'selected_https': 'foreground = "#fff"',
187 'selected_https_text': 'foreground = "gold"',
189 } # End of config dict.
191 # This is the tab style policy handler. Every time the tablist is updated
192 # this function is called to determine how to colourise that specific tab
193 # according the simple/complex rules as defined here. You may even wish to
194 # move this function into another python script and import it using:
195 # from mycustomtabbingconfig import colour_selector
196 # Remember to rename, delete or comment out this function if you do that.
198 def colour_selector(tabindex, currentpage, uzbl):
199 '''Tablist styling policy handler. This function must return a tuple of
200 the form (tab style, text style).'''
202 # Just as an example:
203 # if 'error' in uzbl.title:
204 # if tabindex == currentpage:
205 # return ('foreground="#fff"', 'foreground="red"')
206 # return ('foreground="#888"', 'foreground="red"')
208 # Style tabs to indicate connected via https.
209 if config['tab_indicate_https'] and uzbl.uri.startswith("https://"):
210 if tabindex == currentpage:
211 return (config['selected_https'], config['selected_https_text'])
212 return (config['https_colours'], config['https_text_colours'])
214 # Style to indicate selected.
215 if tabindex == currentpage:
216 return (config['selected_tab'], config['selected_tab_text'])
219 return (config['tab_colours'], config['tab_text_colours'])
222 # ============================================================================
223 # ::: End of configuration section :::::::::::::::::::::::::::::::::::::::::::
224 # ============================================================================
227 def readconfig(uzbl_config, config):
228 '''Loads relevant config from the users uzbl config file into the global
229 config dictionary.'''
231 if not os.path.exists(uzbl_config):
232 error("Unable to load config %r" % uzbl_config)
235 # Define parsing regular expressions
236 isint = re.compile("^(\-|)[0-9]+$").match
237 findsets = re.compile("^set\s+([^\=]+)\s*\=\s*(.+)$",\
238 re.MULTILINE).findall
240 h = open(os.path.expandvars(uzbl_config), 'r')
244 for (key, value) in findsets(rawconfig):
245 key, value = key.strip(), value.strip()
246 if key not in config.keys(): continue
247 if isint(value): value = int(value)
250 # Ensure that config keys that relate to paths are expanded.
251 expand = ['fifo_dir', 'socket_dir', 'session_file', 'icon_path']
253 config[key] = os.path.expandvars(config[key])
257 '''Recursively make directories.
258 I.e. `mkdir -p /some/nonexistant/path/`'''
260 path, sep = os.path.realpath(path), os.path.sep
261 dirs = path.split(sep)
262 for i in range(2,len(dirs)+1):
263 dir = os.path.join(sep,sep.join(dirs[:i]))
264 if not os.path.exists(dir):
269 '''To infinity and beyond!'''
278 '''Generates a random md5 for socket message-termination endmarkers.'''
280 return hashlib.md5(str(random.random()*time.time())).hexdigest()
284 '''A tabbed version of uzbl using gtk.Notebook'''
287 '''Uzbl instance meta-data/meta-action object.'''
289 def __init__(self, parent, tab, fifo_socket, socket_file, pid,\
294 self.fifo_socket = fifo_socket
295 self.socket_file = socket_file
297 self.title = config['new_tab_title']
305 # Switch to tab after loading
306 self._switch = switch
307 # fifo/socket files exists and socket connected.
308 self._connected = False
312 # Message termination endmarker.
313 self._marker = gen_endmarker()
315 # Gen probe commands string
317 probe = probes.append
318 probe('print uri %d @uri %s' % (self.pid, self._marker))
319 probe('print title %d @<document.title>@ %s' % (self.pid,\
321 self._probecmds = '\n'.join(probes)
323 # Enqueue keybinding config for child uzbl instance
324 self.parent.config_uzbl(self)
327 def flush(self, timer_call=False):
328 '''Flush messages from the socket-out and fifo-out queues.'''
335 error("Flush called on dead tab.")
338 if len(self._fifoout):
339 if os.path.exists(self.fifo_socket):
340 h = open(self.fifo_socket, 'w')
341 while len(self._fifoout):
342 msg = self._fifoout.pop(0)
346 if len(self._socketout):
347 if not self._socket and os.path.exists(self.socket_file):
348 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
349 sock.connect(self.socket_file)
353 while len(self._socketout):
354 msg = self._socketout.pop(0)
355 self._socket.send("%s\n"%msg)
357 if not self._connected and timer_call:
358 if not len(self._fifoout + self._socketout):
359 self._connected = True
361 if timer_call in self.timers.keys():
362 gobject.source_remove(self.timers[timer_call])
363 del self.timers[timer_call]
368 return len(self._fifoout + self._socketout)
372 '''Steal parent focus and switch the notebook to my own tab.'''
374 tabs = list(self.parent.notebook)
375 tabid = tabs.index(self.tab)
376 self.parent.goto_tab(tabid)
380 '''Probes the client for information about its self.'''
383 self.send(self._probecmds)
384 self._lastprobe = time.time()
387 def write(self, msg):
388 '''Child fifo write function.'''
390 self._fifoout.append(msg)
391 # Flush messages from the queue if able.
396 '''Child socket send function.'''
398 self._socketout.append(msg)
399 # Flush messages from queue if able.
404 '''Create tablist, window and notebook.'''
410 # Once a second is updated with the latest tabs' uris so that when the
411 # window is killed the session is saved.
413 # And index of current page in self._tabsuris
416 # Holds metadata on the uzbl childen open.
419 # Generates a unique id for uzbl socket filenames.
420 self.next_pid = counter().next
423 self.window = gtk.Window()
425 window_size = map(int, config['window_size'].split(','))
426 self.window.set_default_size(*window_size)
429 error("Invalid value for default_size in config file.")
431 self.window.set_title("Uzbl Browser")
432 self.window.set_border_width(0)
434 # Set main window icon
435 icon_path = config['icon_path']
436 if os.path.exists(icon_path):
437 self.window.set_icon(gtk.gdk.pixbuf_new_from_file(icon_path))
440 icon_path = '/usr/share/uzbl/examples/data/uzbl/uzbl.png'
441 if os.path.exists(icon_path):
442 self.window.set_icon(gtk.gdk.pixbuf_new_from_file(icon_path))
444 # Attach main window event handlers
445 self.window.connect("delete-event", self.quit)
448 if config['show_tablist']:
450 self.window.add(vbox)
451 ebox = gtk.EventBox()
452 self.tablist = gtk.Label()
453 self.tablist.set_use_markup(True)
454 self.tablist.set_justify(gtk.JUSTIFY_LEFT)
455 self.tablist.set_line_wrap(False)
456 self.tablist.set_selectable(False)
457 self.tablist.set_padding(2,2)
458 self.tablist.set_alignment(0,0)
459 self.tablist.set_ellipsize(pango.ELLIPSIZE_END)
460 self.tablist.set_text(" ")
462 ebox.add(self.tablist)
464 bgcolor = gtk.gdk.color_parse(config['status_background'])
465 ebox.modify_bg(gtk.STATE_NORMAL, bgcolor)
468 self.notebook = gtk.Notebook()
469 self.notebook.set_show_tabs(config['show_gtk_tabs'])
472 allposes = {'left': gtk.POS_LEFT, 'right':gtk.POS_RIGHT,
473 'top':gtk.POS_TOP, 'bottom':gtk.POS_BOTTOM}
474 if config['gtk_tab_pos'] in allposes.keys():
475 self.notebook.set_tab_pos(allposes[config['gtk_tab_pos']])
477 self.notebook.set_show_border(False)
478 self.notebook.set_scrollable(True)
479 self.notebook.set_border_width(0)
481 self.notebook.connect("page-removed", self.tab_closed)
482 self.notebook.connect("switch-page", self.tab_changed)
483 self.notebook.connect("page-added", self.tab_opened)
486 if config['show_tablist']:
487 if config['tablist_top']:
488 vbox.pack_start(ebox, False, False, 0)
489 vbox.pack_end(self.notebook, True, True, 0)
492 vbox.pack_start(self.notebook, True, True, 0)
493 vbox.pack_end(ebox, False, False, 0)
498 self.window.add(self.notebook)
501 self.wid = self.notebook.window.xid
503 # Create the uzbl_tabbed fifo
504 fifo_filename = 'uzbltabbed_%d' % os.getpid()
505 self.fifo_socket = os.path.join(config['fifo_dir'], fifo_filename)
506 self._create_fifo_socket(self.fifo_socket)
507 self._setup_fifo_watcher(self.fifo_socket)
510 def _create_fifo_socket(self, fifo_socket):
511 '''Create interprocess communication fifo socket.'''
513 if os.path.exists(fifo_socket):
514 if not os.access(fifo_socket, os.F_OK | os.R_OK | os.W_OK):
515 os.mkfifo(fifo_socket)
518 basedir = os.path.dirname(self.fifo_socket)
519 if not os.path.exists(basedir):
521 os.mkfifo(self.fifo_socket)
523 print "Listening on %s" % self.fifo_socket
526 def _setup_fifo_watcher(self, fifo_socket):
527 '''Open fifo socket fd and setup gobject IO_IN & IO_HUP watchers.
528 Also log the creation of a fd and store the the internal
529 self._watchers dictionary along with the filename of the fd.'''
531 if fifo_socket in self._fifos.keys():
532 fd, watchers = self._fifos[fifo_socket]
534 for watcherid in watchers.keys():
535 gobject.source_remove(watchers[watcherid])
536 del watchers[watcherid]
538 del self._fifos[fifo_socket]
540 # Re-open fifo and add listeners.
541 fd = os.open(fifo_socket, os.O_RDONLY | os.O_NONBLOCK)
543 self._fifos[fifo_socket] = (fd, watchers)
544 watcher = lambda key, id: watchers.__setitem__(key, id)
546 # Watch for incoming data.
547 gid = gobject.io_add_watch(fd, gobject.IO_IN, self.main_fifo_read)
548 watcher('main-fifo-read', gid)
550 # Watch for fifo hangups.
551 gid = gobject.io_add_watch(fd, gobject.IO_HUP, self.main_fifo_hangup)
552 watcher('main-fifo-hangup', gid)
556 '''UzblTabbed main function that calls the gtk loop.'''
558 # Update tablist timer
559 #timer = "update-tablist"
560 #timerid = gobject.timeout_add(500, self.update_tablist,timer)
561 #self._timers[timer] = timerid
563 # Probe clients every second for window titles and location
564 timer = "probe-clients"
565 timerid = gobject.timeout_add(1000, self.probe_clients, timer)
566 self._timers[timer] = timerid
571 def probe_clients(self, timer_call):
572 '''Probe all uzbl clients for up-to-date window titles and uri's.'''
576 tabskeys = self.tabs.keys()
577 notebooklist = list(self.notebook)
579 for tab in notebooklist:
580 if tab not in tabskeys: continue
581 uzbl = self.tabs[tab]
582 uriinventory.append(uzbl.uri)
585 sockd[uzbl._socket] = uzbl
587 self._tabsuris = uriinventory
588 self._curpage = self.notebook.get_current_page()
590 sockets = sockd.keys()
591 (reading, _, errors) = select.select(sockets, [], sockets, 0)
595 uzbl._buffer = sock.recv(1024).replace('\n',' ')
596 temp = uzbl._buffer.split(uzbl._marker)
597 self._buffer = temp.pop()
598 cmds = [s.strip().split() for s in temp if len(s.strip())]
602 self.parse_command(cmd)
605 error("parse_command: invalid command %s" % ' '.join(cmd))
611 def main_fifo_hangup(self, fd, cb_condition):
612 '''Handle main fifo socket hangups.'''
614 # Close fd, re-open fifo_socket and watch.
615 self._setup_fifo_watcher(self.fifo_socket)
617 # And to kill any gobject event handlers calling this function:
621 def main_fifo_read(self, fd, cb_condition):
622 '''Read from main fifo socket.'''
624 self._buffer = os.read(fd, 1024)
625 temp = self._buffer.split("\n")
626 self._buffer = temp.pop()
627 cmds = [s.strip().split() for s in temp if len(s.strip())]
632 self.parse_command(cmd)
635 error("parse_command: invalid command %s" % ' '.join(cmd))
641 def parse_command(self, cmd):
642 '''Parse instructions from uzbl child processes.'''
644 # Commands ( [] = optional, {} = required )
646 # open new tab and head to optional uri.
648 # close current tab or close via tab id.
650 # open next tab or n tabs down. Supports negative indexing.
652 # open prev tab or n tabs down. Supports negative indexing.
659 # title {pid} {document-title}
660 # updates tablist title.
661 # uri {pid} {document-location}
670 elif cmd[0] == "newfromclip":
671 uri = subprocess.Popen(['xclip','-selection','clipboard','-o'],\
672 stdout=subprocess.PIPE).communicate()[0]
676 elif cmd[0] == "close":
678 self.close_tab(int(cmd[1]))
683 elif cmd[0] == "next":
685 self.next_tab(int(cmd[1]))
690 elif cmd[0] == "prev":
692 self.prev_tab(int(cmd[1]))
697 elif cmd[0] == "goto":
698 self.goto_tab(int(cmd[1]))
700 elif cmd[0] == "first":
703 elif cmd[0] == "last":
706 elif cmd[0] in ["title", "uri"]:
708 uzbl = self.get_tab_by_pid(int(cmd[1]))
710 old = getattr(uzbl, cmd[0])
711 new = ' '.join(cmd[2:])
712 setattr(uzbl, cmd[0], new)
714 self.update_tablist()
716 error("parse_command: no uzbl with pid %r" % int(cmd[1]))
718 error("parse_command: unknown command %r" % ' '.join(cmd))
721 def get_tab_by_pid(self, pid):
722 '''Return uzbl instance by pid.'''
724 for tab in self.tabs.keys():
725 if self.tabs[tab].pid == pid:
726 return self.tabs[tab]
731 def new_tab(self, uri='', switch=None):
732 '''Add a new tab to the notebook and start a new instance of uzbl.
733 Use the switch option to negate config['switch_to_new_tabs'] option
734 when you need to load multiple tabs at a time (I.e. like when
735 restoring a session from a file).'''
737 pid = self.next_pid()
740 self.notebook.append_page(tab)
743 fifo_filename = 'uzbl_fifo_%s_%0.2d' % (self.wid, pid)
744 fifo_socket = os.path.join(config['fifo_dir'], fifo_filename)
745 socket_filename = 'uzbl_socket_%s_%0.2d' % (self.wid, pid)
746 socket_file = os.path.join(config['socket_dir'], socket_filename)
749 switch = config['switch_to_new_tabs']
752 # Create meta-instance and spawn child
754 uri = '--uri %s' % uri
756 uzbl = self.UzblInstance(self, tab, fifo_socket, socket_file, pid,\
758 self.tabs[tab] = uzbl
759 cmd = 'uzbl -s %s -n %s_%0.2d %s &' % (sid, self.wid, pid, uri)
760 subprocess.Popen([cmd], shell=True) # TODO: do i need close_fds=True ?
762 # Add gobject timer to make sure the config is pushed when fifo socket
764 timerid = gobject.timeout_add(100, uzbl.flush, "flush-initial-config")
765 uzbl.timers['flush-initial-config'] = timerid
767 self.update_tablist()
770 def config_uzbl(self, uzbl):
771 '''Send bind commands for tab new/close/next/prev to a uzbl
775 bind_format = 'bind %s = sh "echo \\\"%s\\\" > \\\"%s\\\""'
776 bind = lambda key, action: binds.append(bind_format % (key, action, \
779 # Keys are defined in the config section
780 # bind ( key , command back to fifo )
781 bind(config['bind_new_tab'], 'new')
782 bind(config['bind_tab_from_clip'], 'newfromclip')
783 bind(config['bind_tab_from_uri'], 'new %s')
784 bind(config['bind_close_tab'], 'close')
785 bind(config['bind_next_tab'], 'next')
786 bind(config['bind_prev_tab'], 'prev')
787 bind(config['bind_goto_tab'], 'goto %s')
788 bind(config['bind_goto_first'], 'goto 0')
789 bind(config['bind_goto_last'], 'goto -1')
791 # uzbl.send via socket or uzbl.write via fifo, I'll try send.
792 uzbl.send("\n".join(binds))
795 def goto_tab(self, index):
796 '''Goto tab n (supports negative indexing).'''
798 tabs = list(self.notebook)
799 if 0 <= index < len(tabs):
800 self.notebook.set_current_page(index)
801 self.update_tablist()
806 # Update index because index might have previously been a
808 index = tabs.index(tab)
809 self.notebook.set_current_page(index)
810 self.update_tablist()
816 def next_tab(self, step=1):
817 '''Switch to next tab or n tabs right.'''
820 error("next_tab: invalid step %r" % step)
823 ntabs = self.notebook.get_n_pages()
824 tabn = (self.notebook.get_current_page() + step) % ntabs
825 self.notebook.set_current_page(tabn)
826 self.update_tablist()
829 def prev_tab(self, step=1):
830 '''Switch to prev tab or n tabs left.'''
833 error("prev_tab: invalid step %r" % step)
836 ntabs = self.notebook.get_n_pages()
837 tabn = self.notebook.get_current_page() - step
838 while tabn < 0: tabn += ntabs
839 self.notebook.set_current_page(tabn)
840 self.update_tablist()
843 def close_tab(self, tabn=None):
844 '''Closes current tab. Supports negative indexing.'''
847 tabn = self.notebook.get_current_page()
851 tab = list(self.notebook)[tabn]
854 error("close_tab: invalid index %r" % tabn)
857 self.notebook.remove_page(tabn)
860 def tab_opened(self, notebook, tab, index):
861 '''Called upon tab creation. Called by page-added signal.'''
863 if config['switch_to_new_tabs']:
864 self.notebook.set_focus_child(tab)
867 oldindex = self.notebook.get_current_page()
868 oldtab = self.notebook.get_nth_page(oldindex)
869 self.notebook.set_focus_child(oldtab)
872 def tab_closed(self, notebook, tab, index):
873 '''Close the window if no tabs are left. Called by page-removed
876 if tab in self.tabs.keys():
877 uzbl = self.tabs[tab]
878 for timer in uzbl.timers.keys():
879 error("tab_closed: removing timer %r" % timer)
880 gobject.source_remove(uzbl.timers[timer])
891 if self.notebook.get_n_pages() == 0:
894 self.update_tablist()
899 def tab_changed(self, notebook, page, index):
900 '''Refresh tab list. Called by switch-page signal.'''
902 tab = self.notebook.get_nth_page(index)
903 self.notebook.set_focus_child(tab)
904 self.update_tablist(index)
908 def update_tablist(self, curpage=None):
909 '''Upate tablist status bar.'''
911 show_tablist = config['show_tablist']
912 show_gtk_tabs = config['show_gtk_tabs']
913 tab_titles = config['tab_titles']
914 show_ellipsis = config['show_ellipsis']
915 if not show_tablist and not show_gtk_tabs:
918 tabs = self.tabs.keys()
920 curpage = self.notebook.get_current_page()
922 title_format = "%s - Uzbl Browser"
923 max_title_len = config['max_title_len']
927 normal = (config['tab_colours'], config['tab_text_colours'])
928 selected = (config['selected_tab'], config['selected_tab_text'])
930 tab_format = "<span %s> [ %d <span %s> %s</span> ] </span>"
932 tab_format = "<span %s> [ <span %s>%d</span> ] </span>"
935 gtk_tab_format = "%d %s"
937 for index, tab in enumerate(self.notebook):
938 if tab not in tabs: continue
939 uzbl = self.tabs[tab]
942 self.window.set_title(title_format % uzbl.title)
944 tabtitle = uzbl.title[:max_title_len]
945 if show_ellipsis and len(tabtitle) != len(uzbl.title):
946 tabtitle = "%s\xe2\x80\xa6" % tabtitle[:-1] # Show Ellipsis
950 self.notebook.set_tab_label_text(tab,\
951 gtk_tab_format % (index, tabtitle))
953 self.notebook.set_tab_label_text(tab, str(index))
956 style = colour_selector(index, curpage, uzbl)
957 (tabc, textc) = style
960 pango += tab_format % (tabc, index, textc, tabtitle)
962 pango += tab_format % (tabc, textc, index)
965 self.tablist.set_markup(pango)
970 def quit(self, *args):
971 '''Cleanup the application and quit. Called by delete-event signal.'''
973 for fifo_socket in self._fifos.keys():
974 fd, watchers = self._fifos[fifo_socket]
976 for watcherid in watchers.keys():
977 gobject.source_remove(watchers[watcherid])
978 del watchers[watcherid]
980 del self._fifos[fifo_socket]
982 for timerid in self._timers.keys():
983 gobject.source_remove(self._timers[timerid])
984 del self._timers[timerid]
986 if os.path.exists(self.fifo_socket):
987 os.unlink(self.fifo_socket)
988 print "Unlinked %s" % self.fifo_socket
990 if config['save_session']:
991 session_file = config['session_file']
992 if len(self._tabsuris):
993 if not os.path.isfile(session_file):
994 dirname = os.path.dirname(session_file)
995 if not os.path.isdir(dirname):
996 # Recursive mkdir not rmdir.
999 sessionstr = '\n'.join(self._tabsuris)
1000 h = open(session_file, 'w')
1001 h.write('current = %s\n%s' % (self._curpage, sessionstr))
1005 # Notebook has no pages so delete session file if it exists.
1006 if os.path.isfile(session_file):
1007 os.remove(session_file)
1012 if __name__ == "__main__":
1014 # Read from the uzbl config into the global config dictionary.
1015 readconfig(uzbl_config, config)
1019 if os.path.isfile(os.path.expandvars(config['session_file'])):
1020 h = open(os.path.expandvars(config['session_file']),'r')
1021 lines = [line.strip() for line in h.readlines()]
1026 if line.startswith("current"):
1027 current = int(line.split()[-1])
1030 urls.append(line.strip())
1032 for (index, url) in enumerate(urls):
1033 if current == index:
1034 uzbl.new_tab(line, True)
1037 uzbl.new_tab(line, False)