generate a handful of files with substitutions from config.mk
[wmiirc-lua.git] / src / core / wmii.lua.in
blobf69881c7918bccb94df90fef3184ed020aa5bc95
1 --
2 -- Copyright (c) 2007, Bart Trojanowski <bart@jukie.net>
3 --
4 -- WMII event loop, in lua
5 --
6 -- http://www.jukie.net/~bart/blog/tag/wmiirc-lua
7 -- git://www.jukie.net/wmiirc-lua.git/
8 --
10 -- ========================================================================
11 -- DOCUMENTATION
12 -- ========================================================================
13 --[[
14 =pod
16 =head1 NAME
18 wmii.lua - WMII event-loop methods in lua
20 =head1 SYNOPSIS
22 require "wmii"
24 -- Write something to the wmii filesystem, in this case a key event.
25 wmii.write ("/event", "Key Mod1-j")
27 -- Set your wmii /ctl parameters
28 wmii.set_ctl({
29 font = '....'
32 -- Configure wmii.lua parameters
33 wmii.set_conf ({
34 xterm = 'x-terminal-emulator'
37 -- Now start the event loop
38 wmii.run_event_loop()
40 =head1 DESCRIPTION
42 wmii.lua provides methods for replacing the stock sh-based wmiirc shipped with
43 wmii 3.6 and newer with a lua-based event loop.
45 It should be used by your wmiirc
47 =head1 METHODS
49 =over 4
51 =cut
52 --]]
54 -- ========================================================================
55 -- MODULE SETUP
56 -- ========================================================================
58 local wmiidir = ("%HOME_WMII%"):gsub("^~", os.getenv("HOME"))
59 local wmiirc = wmiidir .. "/wmiirc"
61 package.path = wmiidir .. "/core/?.lua;" ..
62 wmiidir .. "/plugins/?.lua;" ..
63 package.path
64 package.cpath = wmiidir .. "/core/?.so;" ..
65 wmiidir .. "/plugins/?.so;" ..
66 package.cpath
68 local ixp = require "ixp"
69 local eventloop = require "eventloop"
70 local history = require "history"
72 local io = require("io")
73 local os = require("os")
74 local string = require("string")
75 local table = require("table")
76 local math = require("math")
77 local type = type
78 local error = error
79 local print = print
80 local pcall = pcall
81 local pairs = pairs
82 local package = package
83 local require = require
84 local tostring = tostring
85 local tonumber = tonumber
86 local setmetatable = setmetatable
88 -- kinda silly, but there is no working liblua5.1-posix0 in ubuntu
89 -- so we make it optional
90 local have_posix, posix = pcall(require,"posix")
92 module("wmii")
94 -- get the process id
95 local myid
96 if have_posix then
97 -- but having posix is not enough as the API changes, so we try each one
98 if posix.getprocessid then
99 local stat,rc = pcall (posix.getprocessid, "pid")
100 if stat then
101 myid = rc
104 if not myid and posix.getpid then
105 local stat,rc = pcall (posix.getpid, "pid")
106 if stat then
107 myid = rc
111 if not myid then
112 -- we were not able to get the PID, but we can create a random number
113 local now = tonumber(os.date("%s"))
114 math.randomseed(now)
115 myid = math.random(10000)
118 -- ========================================================================
119 -- MODULE VARIABLES
120 -- ========================================================================
122 -- wmiir points to the wmiir executable
123 -- TODO: need to make sure that wmiir is in path, and if not find it
124 local wmiir = "wmiir"
126 -- wmii_adr is the address we use when connecting using ixp
127 local wmii_adr = os.getenv("WMII_ADDRESS")
128 or ("unix!/tmp/ns." .. os.getenv("USER") .. "."
129 .. os.getenv("DISPLAY"):match("(:%d+)") .. "/wmii")
131 -- wmixp is the ixp context we use to talk to wmii
132 local wmixp = ixp.new(wmii_adr)
134 -- history of previous views, view_hist[#view_hist] is the last one
135 local view_hist = {} -- sorted with 1 being the oldest
136 local view_hist_max = 50 -- max number to keep track of
138 -- allow for a client to be forced to a tag
139 local next_client_goes_to_tag = nil
141 -- program and action histories
142 local prog_hist = history.new (20)
143 local action_hist = history.new(10)
145 -- where to find plugins
146 plugin_path = wmiidir .. "/plugins/?.so;"
147 .. wmiidir .. "/plugins/?.lua;"
148 .. "/usr/local/lib/lua/5.1/wmii/?.so;"
149 .. "/usr/local/share/lua/5.1/wmii/?.lua;"
150 .. "/usr/lib/lua/5.1/wmii/?.so;"
151 .. "/usr/share/lua/5.1/wmii/?.lua"
153 -- where to find wmiirc (see find_wmiirc())
154 wmiirc_path = wmiidir .. "/wmiirc.lua;"
155 .. wmiidir .. "/wmiirc;"
156 .. "%RC_DIR%/wmiirc.lua;"
157 .. "%RC_DIR%/wmiirc"
159 -- ========================================================================
160 -- LOCAL HELPERS
161 -- ========================================================================
163 --[[
164 =pod
166 =item log ( str )
168 Log the message provided in C<str>
170 Currently just writes to io.stderr
172 =cut
173 --]]
174 function log (str)
175 if get_conf("debug") then
176 io.stderr:write (str .. "\n")
180 --[[
181 =pod
183 =item find_wmiirc ( )
185 Locates the wmiirc script. It looks in %HOME_WMII% and %RC_DIR%
186 for the first lua script bearing the name wmiirc.lua or wmiirc. Returns
187 first match.
189 =cut
190 --]]
191 function find_wmiirc()
192 local fn
193 for fn in string.gmatch(wmiirc_path, "[^;]+") do
194 -- try to locate the files locally
195 local file = io.open(fn, "r")
196 if file then
197 local txt = file:read("*line")
198 file:close()
199 if type(txt) == 'string' and txt:match("lua") then
200 return fn
204 return nil
208 -- ========================================================================
209 -- MAIN ACCESS FUNCTIONS
210 -- ========================================================================
212 --[[
213 =pod
215 =item ls ( dir, fmt )
217 List the wmii filesystem directory provided in C<dir>, in the format specified
218 by C<fmt>.
220 Returns an iterator of TODO
222 =cut
223 --]]
224 function ls (dir, fmt)
225 local verbose = fmt and fmt:match("l")
227 local s = wmixp:stat(dir)
228 if not s then
229 return function () return nil end
231 if s.modestr:match("^[^d]") then
232 return function ()
233 return stat2str(verbose, s)
237 local itr = wmixp:idir (dir)
238 if not itr then
239 --return function ()
240 return nil
241 --end
245 return function ()
246 local s = itr()
247 if s then
248 return stat2str(verbose, s)
250 return nil
254 local function stat2str(verbose, stat)
255 if verbose then
256 return string.format("%s %s %s %5d %s %s", stat.modestr, stat.uid, stat.gid, stat.length, stat.timestr, stat.name)
257 else
258 if stat.modestr:match("^d") then
259 return stat.name .. "/"
260 else
261 return stat.name
266 -- ------------------------------------------------------------------------
267 -- read all contents of a wmii virtual file
268 function read (file)
269 return wmixp:read (file)
272 -- ------------------------------------------------------------------------
273 -- return an iterator which walks all the lines in the file
275 -- example:
276 -- for event in wmii.iread("/ctl")
277 -- ...
278 -- end
280 -- NOTE: don't use iread for files that could block, as this will interfere
281 -- with timer processing and event delivery. Instead fork off a process to
282 -- execute wmiir and read back the responses via callback.
283 function iread (file)
284 return wmixp:iread(file)
287 -- ------------------------------------------------------------------------
288 -- create a wmii file, optionally write data to it
289 function create (file, data)
290 wmixp:create(file, data)
293 -- ------------------------------------------------------------------------
294 -- remove a wmii file
295 function remove (file)
296 wmixp:remove(file)
299 -- ------------------------------------------------------------------------
300 -- write a value to a wmii virtual file system
301 function write (file, value)
302 wmixp:write (file, value)
305 -- ------------------------------------------------------------------------
306 -- setup a table describing the menu command
307 local function menu_cmd (prompt)
308 local cmdt = { wmiir, "setsid", "dmenu", "-b" }
309 local fn = get_ctl("font")
310 if fn then
311 cmdt[#cmdt+1] = "-fn"
312 cmdt[#cmdt+1] = fn
314 local normcolors = get_ctl("normcolors")
315 if normcolors then
316 local nf, nb = normcolors:match("(#%x+)%s+(#%x+)%s#%x+")
317 if nf then
318 cmdt[#cmdt+1] = "-nf"
319 cmdt[#cmdt+1] = "'" .. nf .. "'"
321 if nb then
322 cmdt[#cmdt+1] = "-nb"
323 cmdt[#cmdt+1] = "'" .. nb .. "'"
326 local focuscolors = get_ctl("focuscolors")
327 if focuscolors then
328 local sf, sb = focuscolors:match("(#%x+)%s+(#%x+)%s#%x+")
329 if sf then
330 cmdt[#cmdt+1] = "-sf"
331 cmdt[#cmdt+1] = "'" .. sf .. "'"
333 if sb then
334 cmdt[#cmdt+1] = "-sb"
335 cmdt[#cmdt+1] = "'" .. sb .. "'"
338 if prompt then
339 cmdt[#cmdt+1] = "-p"
340 cmdt[#cmdt+1] = "'" .. prompt .. "'"
343 return cmdt
346 -- ------------------------------------------------------------------------
347 -- displays the menu given an table of entires, returns selected text
348 function menu (tbl, prompt)
349 local menu = menu_cmd(prompt)
351 local infile = os.tmpname()
352 local fh = io.open (infile, "w+")
354 local i,v
355 for i,v in pairs(tbl) do
356 if type(i) == 'number' and type(v) == 'string' then
357 fh:write (v)
358 else
359 fh:write (i)
361 fh:write ("\n")
363 fh:close()
365 local outfile = os.tmpname()
367 menu[#menu+1] = "<"
368 menu[#menu+1] = infile
369 menu[#menu+1] = ">"
370 menu[#menu+1] = outfile
372 local cmd = table.concat(menu," ")
373 os.execute (cmd)
375 fh = io.open (outfile, "r")
376 os.remove (outfile)
378 local sel = fh:read("*l")
379 fh:close()
381 return sel
384 -- ------------------------------------------------------------------------
385 -- displays the a tag selection menu, returns selected tag
386 function tag_menu ()
387 local tags = get_tags()
389 return menu(tags, "tag:")
392 -- ------------------------------------------------------------------------
393 -- displays the a program menu, returns selected program
394 function prog_menu ()
395 local menu = menu_cmd("cmd:")
397 local outfile = os.tmpname()
399 menu[#menu+1] = ">"
400 menu[#menu+1] = outfile
402 local hstt = { }
403 for n in prog_hist:walk_reverse_unique() do
404 hstt[#hstt+1] = "echo '" .. n .. "' ; "
407 local cmd = "(" .. table.concat(hstt)
408 .. "dmenu_path ) |"
409 .. table.concat(menu," ")
410 os.execute (cmd)
412 local fh = io.open (outfile, "rb")
413 os.remove (outfile)
415 local prog = fh:read("*l")
416 io.close (fh)
418 return prog
421 -- ------------------------------------------------------------------------
422 -- returns a table of sorted tags names
423 function get_tags()
424 local t = {}
425 local s
426 for s in wmixp:idir ("/tag") do
427 if s.name and not (s.name == "sel") then
428 t[#t + 1] = s.name
431 table.sort(t)
432 return t
435 -- ------------------------------------------------------------------------
436 -- returns a table of sorted screen names
437 function get_screens()
438 local t = {}
439 local s
440 local empty = true
441 for s in wmixp:idir ("/screen") do
442 if s.name and not (s.name == "sel") then
443 t[#t + 1] = s.name
444 empty = false
447 if empty then
448 return nil
450 table.sort(t)
451 return t
454 -- ------------------------------------------------------------------------
455 -- returns current view, on current screen or specified screen
456 function get_view(screen)
457 return get_screen_ctl(screen, "view") or get_ctl("view")
460 -- ------------------------------------------------------------------------
461 -- changes the current view to the name given
462 function set_view(sel)
463 local cur = get_view()
464 local all = get_tags()
466 if #all < 2 or sel == cur then
467 -- nothing to do if we have less then 2 tags
468 return
471 if not (type(sel) == "string") then
472 error ("string argument expected")
475 -- set new view
476 write ("/ctl", "view " .. sel)
479 -- ------------------------------------------------------------------------
480 -- changes the current view to the index given
481 function set_view_index(sel)
482 local cur = get_view()
483 local all = get_tags()
485 if #all < 2 then
486 -- nothing to do if we have less then 2 tags
487 return
490 local num = tonumber (sel)
491 if not num then
492 error ("number argument expected")
495 local name = all[sel]
496 if not name or name == cur then
497 return
500 -- set new view
501 write ("/ctl", "view " .. name)
504 -- ------------------------------------------------------------------------
505 -- chnages to current view by offset given
506 function set_view_ofs(jump)
507 local cur = get_view()
508 local all = get_tags()
510 if #all < 2 then
511 -- nothing to do if we have less then 2 tags
512 return
515 -- range check
516 if (jump < - #all) or (jump > #all) then
517 error ("view selector is out of range")
520 -- find the one that's selected index
521 local curi = nil
522 local i,v
523 for i,v in pairs (all) do
524 if v == cur then curi = i end
527 -- adjust by index
528 local newi = math.fmod(#all + curi + jump - 1, #all) + 1
529 if (newi < - #all) or (newi > #all) then
530 error ("error computng new view")
533 write ("/ctl", "view " .. all[newi])
536 -- ------------------------------------------------------------------------
537 -- toggle between last view and current view
538 function toggle_view()
539 local last = view_hist[#view_hist]
540 if last then
541 set_view(last)
545 -- ========================================================================
546 -- ACTION HANDLERS
547 -- ========================================================================
549 local action_handlers = {
550 man = function (act, args)
551 local xterm = get_conf("xterm") or "xterm"
552 local page = args
553 if (not page) or (not page:match("%S")) then
554 page = wmiidir .. "/wmii.3lua"
556 local cmd = xterm .. " -e man " .. page .. " &"
557 log (" executing: " .. cmd)
558 os.execute (wmiir .. " setsid " .. cmd)
559 end,
561 quit = function ()
562 write ("/ctl", "quit")
563 end,
565 exec = function (act, args)
566 local what = args or "wmii"
567 log (" asking wmii to exec " .. tostring(what))
568 cleanup()
569 write ("/ctl", "exec " .. what)
570 end,
572 xlock = function (act)
573 local cmd = get_conf("xlock") or "xscreensaver-command --lock"
574 os.execute (wmiir .. " setsid " .. cmd)
575 end,
577 wmiirc = function ()
578 if have_posix then
579 local wmiirc = find_wmiirc()
580 if wmiirc then
581 log (" executing: lua " .. wmiirc)
582 cleanup()
583 posix.exec (wmiirc)
584 posix.exec ("/bin/sh", "-c", "exec lua wmiirc")
585 posix.exec ("%LUA_BIN%", wmiirc)
586 posix.exec ("/usr/bin/lua", wmiirc)
588 else
589 log("sorry cannot restart; you don't have lua's posix library.")
591 end,
593 urgent = function ()
594 wmixp:write ("/client/sel/ctl", "Urgent toggle")
595 end,
597 --[[
598 rehash = function ()
599 -- TODO: consider storing list of executables around, and
600 -- this will then reinitialize that list
601 log (" TODO: rehash")
602 end,
604 status = function ()
605 -- TODO: this should eventually update something on the /rbar
606 log (" TODO: status")
607 end,
608 --]]
611 --[[
612 =pod
614 =item add_action_handler (action, fn)
616 Add an Alt-a action handler callback function, I<fn>, for the given action string I<action>.
618 =cut
619 --]]
620 function add_action_handler (action, fn)
622 if type(action) ~= "string" or type(fn) ~= "function" then
623 error ("expecting a string and a function")
626 if action_handlers[action] then
627 error ("action handler already exists for '" .. action .. "'")
630 action_handlers[action] = fn
633 --[[
634 =pod
636 =item remove_action_handler (action)
638 Remove an action handler callback function for the given action string I<action>.
640 =cut
641 --]]
642 function remove_action_handler (action)
644 action_handlers[action] = nil
647 -- ========================================================================
648 -- KEY HANDLERS
649 -- ========================================================================
651 function ke_fullscreen_toggle()
652 wmixp:write ("/client/sel/ctl", "Fullscreen toggle")
655 function ke_view_starting_with_letter (letter)
656 local i,v
658 -- find the view name in history in reverse order
659 for i=#view_hist,1,-1 do
660 v = view_hist[i]
661 if letter == v:sub(1,1) then
662 set_view(v)
663 return true
667 -- otherwise just pick the first view that matches
668 local all = get_tags()
669 for i,v in pairs(all) do
670 if letter == v:sub(1,1) then
671 set_view_index (i)
672 return true
676 return false
679 function ke_handle_action()
680 local actions = { }
681 local seen = {}
683 local n
684 for n in action_hist:walk_reverse() do
685 if not seen[n] then
686 actions[#actions+1] = n
687 seen[n] = 1
691 local v
692 for n,v in pairs(action_handlers) do
693 if not seen[n] then
694 actions[#actions+1] = n
695 seen[n] = 1
699 local text = menu(actions, "action:")
700 if text then
701 log ("Action: " .. text)
702 local act = text
703 local args = nil
704 local si = text:find("%s")
705 if si then
706 act,args = string.match(text .. " ", "(%w+)%s(.+)")
708 if act then
709 local fn = action_handlers[act]
710 if fn then
711 action_hist:add (act)
712 local r, err = pcall (fn, act, args)
713 if not r then
714 log ("WARNING: " .. tostring(err))
722 local key_handlers = {
723 ["*"] = function (key)
724 log ("*: " .. key)
725 end,
727 -- execution and actions
728 ["Mod1-Return"] = function (key)
729 local xterm = get_conf("xterm") or "xterm"
730 log (" executing: " .. xterm)
731 os.execute (wmiir .. " setsid " .. xterm .. " &")
732 end,
733 ["Mod1-Shift-Return"] = function (key)
734 local tag = tag_menu()
735 if tag then
736 local xterm = get_conf("xterm") or "xterm"
737 log (" executing: " .. xterm .. " on: " .. tag)
738 next_client_goes_to_tag = tag
739 os.execute (wmiir .. " setsid " .. xterm .. " &")
741 end,
742 ["Mod1-a"] = function (key)
743 ke_handle_action()
744 end,
745 ["Mod1-p"] = function (key)
746 local prog = prog_menu()
747 if prog then
748 prog_hist:add(prog:match("([^ ]+)"))
749 log (" executing: " .. prog)
750 os.execute (wmiir .. " setsid " .. prog .. " &")
752 end,
753 ["Mod1-Shift-p"] = function (key)
754 local tag = tag_menu()
755 if tag then
756 local prog = prog_menu()
757 if prog then
758 log (" executing: " .. prog .. " on: " .. tag)
759 next_client_goes_to_tag = tag
760 os.execute (wmiir .. " setsid " .. prog .. " &")
763 end,
764 ["Mod1-Shift-c"] = function (key)
765 write ("/client/sel/ctl", "kill")
766 end,
768 -- HJKL active selection
769 ["Mod1-h"] = function (key)
770 write ("/tag/sel/ctl", "select left")
771 end,
772 ["Mod1-l"] = function (key)
773 write ("/tag/sel/ctl", "select right")
774 end,
775 ["Mod1-j"] = function (key)
776 write ("/tag/sel/ctl", "select down")
777 end,
778 ["Mod1-k"] = function (key)
779 write ("/tag/sel/ctl", "select up")
780 end,
782 -- HJKL movement
783 ["Mod1-Shift-h"] = function (key)
784 write ("/tag/sel/ctl", "send sel left")
785 end,
786 ["Mod1-Shift-l"] = function (key)
787 write ("/tag/sel/ctl", "send sel right")
788 end,
789 ["Mod1-Shift-j"] = function (key)
790 write ("/tag/sel/ctl", "send sel down")
791 end,
792 ["Mod1-Shift-k"] = function (key)
793 write ("/tag/sel/ctl", "send sel up")
794 end,
796 -- floating vs tiled
797 ["Mod1-space"] = function (key)
798 write ("/tag/sel/ctl", "select toggle")
799 end,
800 ["Mod1-Shift-space"] = function (key)
801 write ("/tag/sel/ctl", "send sel toggle")
802 end,
804 -- work spaces (# and @ are wildcards for numbers and letters)
805 ["Mod4-#"] = function (key, num)
806 -- first attempt to find a view that starts with the number requested
807 local num_str = tostring(num)
808 if not ke_view_starting_with_letter (num_str) then
809 -- if we fail, then set it to the index requested
810 set_view_index (num)
812 end,
813 ["Mod4-Shift-#"] = function (key, num)
814 write ("/client/sel/tags", tostring(num))
815 end,
816 ["Mod4-@"] = function (key, letter)
817 ke_view_starting_with_letter (letter)
818 end,
819 ["Mod4-Shift-@"] = function (key, letter)
820 local all = get_tags()
821 local i,v
822 for i,v in pairs(all) do
823 if letter == v:sub(1,1) then
824 write ("/client/sel/tags", v)
825 break
828 end,
829 ["Mod1-comma"] = function (key)
830 set_view_ofs (-1)
831 end,
832 ["Mod1-period"] = function (key)
833 set_view_ofs (1)
834 end,
835 ["Mod1-r"] = function (key)
836 -- got to the last view
837 toggle_view()
838 end,
840 -- switching views and retagging
841 ["Mod1-t"] = function (key)
842 -- got to a view
843 local tag = tag_menu()
844 if tag then
845 set_view (tag)
847 end,
848 ["Mod1-Shift-t"] = function (key)
849 -- move selected client to a tag
850 local tag = tag_menu()
851 if tag then
852 write ("/client/sel/tags", tag)
854 end,
855 ["Mod1-Shift-r"] = function (key)
856 -- move selected client to a tag, and follow
857 local tag = tag_menu()
858 if tag then
859 -- get the current window id
860 local xid = wmixp:read("/client/sel/ctl") or ""
862 -- modify the tag
863 write("/client/sel/tags", tag)
865 -- if the client is still in this tag, then
866 -- it might have been a regexp tag... check
867 local test = wmixp:read("/client/sel/ctl")
868 if not test or test ~= xid then
869 -- if the window moved, follow it
870 set_view(tag)
873 end,
874 ["Mod1-Control-t"] = function (key)
875 log (" TODO: Mod1-Control-t: " .. key)
876 end,
878 -- column modes
879 ["Mod1-d"] = function (key)
880 write("/tag/sel/ctl", "colmode sel default-max")
881 end,
882 ["Mod1-s"] = function (key)
883 write("/tag/sel/ctl", "colmode sel stack-max")
884 end,
885 ["Mod1-m"] = function (key)
886 write("/tag/sel/ctl", "colmode sel stack+max")
887 end,
888 ["Mod1-f"] = function (key)
889 ke_fullscreen_toggle()
890 end,
892 -- changing client flags
893 ["Shift-Mod1-f"] = function (key)
894 log ("setting flags")
896 local cli = get_client ()
898 local flags = { "suspend", "raw" }
899 local current_flags = cli:flags_string()
901 local what = menu(flags, "current flags: " .. current_flags .. " toggle:")
903 cli:toggle(what)
904 end,
905 ["Mod4-space"] = function (key)
906 local cli = get_client ()
907 cli:toggle("raw")
908 end,
911 --[[
912 =pod
914 =item add_key_handler (key, fn)
916 Add a keypress handler callback function, I<fn>, for the given key sequence I<key>.
918 =cut
919 --]]
920 function add_key_handler (key, fn)
922 if type(key) ~= "string" or type(fn) ~= "function" then
923 error ("expecting a string and a function")
926 if key_handlers[key] then
927 -- TODO: we may wish to allow multiple handlers for one keypress
928 error ("key handler already exists for '" .. key .. "'")
931 key_handlers[key] = fn
934 --[[
935 =pod
937 =item remove_key_handler (key)
939 Remove an key handler callback function for the given key I<key>.
941 Returns the handler callback function.
943 =cut
944 --]]
945 function remove_key_handler (key)
947 local fn = key_handlers[key]
948 key_handlers[key] = nil
949 return fn
952 --[[
953 =pod
955 =item remap_key_handler (old_key, new_key)
957 Remove a key handler callback function from the given key I<old_key>,
958 and assign it to a new key I<new_key>.
960 =cut
961 --]]
962 function remap_key_handler (old_key, new_key)
964 local fn = remove_key_handler(old_key)
966 return add_key_handler (new_key, fn)
970 -- ------------------------------------------------------------------------
971 -- update the /keys wmii file with the list of all handlers
972 local alphabet="abcdefghijklmnopqrstuvwxyz"
973 function update_active_keys ()
974 local t = {}
975 local x, y
976 for x,y in pairs(key_handlers) do
977 if x:find("%w") then
978 local i = x:find("#$")
979 if i then
980 local j
981 for j=0,9 do
982 t[#t + 1] = x:sub(1,i-1) .. j
984 else
985 i = x:find("@$")
986 if i then
987 local j
988 for j=1,alphabet:len() do
989 local a = alphabet:sub(j,j)
990 t[#t + 1] = x:sub(1,i-1) .. a
992 else
993 t[#t + 1] = tostring(x)
998 local all_keys = table.concat(t, "\n")
999 --log ("setting /keys to...\n" .. all_keys .. "\n");
1000 write ("/keys", all_keys)
1003 -- ------------------------------------------------------------------------
1004 -- update the /lbar wmii file with the current tags
1005 function update_displayed_tags ()
1006 -- list of all screens
1007 local screens = get_screens()
1008 if not screens then
1009 update_displayed_tags_on_screen()
1010 return
1013 local i, s
1014 for i,s in pairs(screens) do
1015 update_displayed_tags_on_screen(s)
1019 function update_displayed_tags_on_screen(s)
1020 local lbar = "/lbar"
1021 if s then
1022 lbar = "/screen/" .. s .. "/lbar"
1025 -- colours for screen
1026 local fc = get_screen_ctl(s, "focuscolors") or get_ctl("focuscolors") or ""
1027 local nc = get_screen_ctl(s, "normcolors") or get_ctl("normcolors") or ""
1029 -- build up a table of existing tags in the /lbar
1030 local old = {}
1031 local ent
1032 for ent in wmixp:idir (lbar) do
1033 old[ent.name] = 1
1036 -- for all actual tags in use create any entries in /lbar we don't have
1037 -- clear the old table entries if we have them
1038 local cur = get_view(s)
1039 local all = get_tags()
1040 local i,v
1041 for i,v in pairs(all) do
1042 local color = nc
1043 if cur == v then
1044 color = fc
1046 if not old[v] then
1047 create (lbar .. "/" .. v, color .. " " .. v)
1049 write (lbar .. "/" .. v, color .. " " .. v)
1050 old[v] = nil
1053 -- anything left in the old table should be removed now
1054 for i,v in pairs(old) do
1055 if v then
1056 remove(lbar.."/"..i)
1060 -- this is a hack, and should brobably be rethought
1061 -- the intent is to distinguish the multiple screens
1062 if s then
1063 create ("/screen/"..s.."/lbar/000000000000000000", '-'..s..'-')
1067 function create_tag_widget(name)
1068 local nc = get_ctl("normcolors") or ""
1069 local screens = get_screens()
1070 if not screens then
1071 create ("/lbar/" .. name, nc .. " " .. name)
1072 return
1074 local i, s
1075 for i,s in pairs(screens) do
1076 create ("/screen/"..s.."/lbar/" .. name, nc .. " " .. name)
1080 function destroy_tag_widget(name)
1081 local screens = get_screens()
1082 if not screens then
1083 remove ("/lbar/" .. name)
1084 return
1086 local i, s
1087 for i,s in pairs(screens) do
1088 remove ("/screen/"..s.."/lbar/" .. name)
1093 -- ========================================================================
1094 -- EVENT HANDLERS
1095 -- ========================================================================
1097 local widget_ev_handlers = {
1100 --[[
1101 =pod
1103 =item _handle_widget_event (ev, arg)
1105 Top-level event handler for redispatching events to widgets. This event
1106 handler is added for any widget event that currently has a widget registered
1107 for it.
1109 Valid widget events are currently
1111 RightBarMouseDown <buttonnumber> <widgetname>
1112 RightBarClick <buttonnumber> <widgetname>
1114 the "Click" event is sent on mouseup.
1116 The callbacks are given only the button number as their argument, to avoid the
1117 need to reparse.
1119 =cut
1120 --]]
1122 local function _handle_widget_event (ev, arg)
1124 log("_handle_widget_event: " .. tostring(ev) .. " - " .. tostring(arg))
1126 -- parse arg to strip out our widget name
1127 local number,wname = string.match(arg, "(%d+)%s+(.+)")
1129 -- check our dispatch table for that widget
1130 if not wname then
1131 log("Didn't find wname")
1132 return
1135 local wtable = widget_ev_handlers[wname]
1136 if not wtable then
1137 log("No widget cares about" .. wname)
1138 return
1141 local fn = wtable[ev] or wtable["*"]
1142 if fn then
1143 success, err = pcall( fn, ev, tonumber(number) )
1144 if not success then
1145 log("Callback had an error in _handle_widget_event: " .. tostring(err) )
1146 return nil
1148 else
1149 log("no function found for " .. ev)
1153 local ev_handlers = {
1154 ["*"] = function (ev, arg)
1155 log ("ev: " .. tostring(ev) .. " - " .. tostring(arg))
1156 end,
1158 RightBarClick = _handle_widget_event,
1160 -- process timer events
1161 ProcessTimerEvents = function (ev, arg)
1162 process_timers()
1163 end,
1165 -- exit if another wmiirc started up
1166 Start = function (ev, arg)
1167 if arg then
1168 if arg == "wmiirc" then
1169 -- backwards compatibility with bash version
1170 log (" exiting; pid=" .. tostring(myid))
1171 cleanup()
1172 os.exit (0)
1173 else
1174 -- ignore if it came from us
1175 local pid = string.match(arg, "wmiirc (%d+)")
1176 if pid then
1177 local pid = tonumber (pid)
1178 if not (pid == myid) then
1179 log (" exiting; pid=" .. tostring(myid))
1180 cleanup()
1181 os.exit (0)
1186 end,
1188 -- tag management
1189 CreateTag = function (ev, arg)
1190 log ("CreateTag: " .. arg)
1191 create_tag_widget(arg)
1192 end,
1193 DestroyTag = function (ev, arg)
1194 log ("DestroyTag: " .. arg)
1195 destroy_tag_widget(arg)
1197 -- remove the tag from history
1198 local i,v
1199 for i=#view_hist,1,-1 do
1200 v = view_hist[i]
1201 if arg == v then
1202 table.remove(view_hist,i)
1205 end,
1207 FocusTag = function (ev, arg)
1208 log ("FocusTag: " .. arg)
1210 local tag,scrn = arg:match("(%w+)%s*(%w*)")
1211 if not tag then
1212 return
1215 local file = "/lbar/" .. tag
1216 if scrn and scrn:len() > 0 then
1217 file = "/screen/" .. scrn .. file
1220 local fc = get_screen_ctl(scrn, "focuscolors") or get_ctl("focuscolors") or ""
1221 log ("# echo " .. fc .. " " .. tag .. " | wmiir write " .. file)
1223 create (file, fc .. " " .. tag)
1224 write (file, fc .. " " .. tag)
1225 end,
1226 UnfocusTag = function (ev, arg)
1227 log ("UnfocusTag: " .. arg)
1229 local tag,scrn = arg:match("(%w+)%s*(%w*)")
1230 if not tag then
1231 return
1234 local file = "/lbar/" .. tag
1235 if scrn and scrn:len() > 0 then
1236 file = "/screen/" .. scrn .. file
1239 local nc = get_screen_ctl(scrn, "normcolors") or get_ctl("normcolors") or ""
1240 log ("# echo " .. nc .. " " .. tag .. " | wmiir write " .. file)
1242 create (file, nc .. " " .. tag)
1243 write (file, nc .. " " .. tag)
1245 -- don't duplicate the last entry
1246 if not (tag == view_hist[#view_hist]) then
1247 view_hist[#view_hist+1] = tag
1249 -- limit to view_hist_max
1250 if #view_hist > view_hist_max then
1251 table.remove(view_hist, 1)
1254 end,
1256 -- key event handling
1257 Key = function (ev, arg)
1258 log ("Key: " .. arg)
1259 local magic = nil
1260 -- can we find an exact match?
1261 local fn = key_handlers[arg]
1262 if not fn then
1263 local key = arg:gsub("-%d$", "-#")
1264 -- can we find a match with a # wild card for the number
1265 fn = key_handlers[key]
1266 if fn then
1267 -- convert the trailing number to a number
1268 magic = tonumber(arg:match("-(%d)$"))
1271 if not fn then
1272 local key = arg:gsub("-%a$", "-@")
1273 -- can we find a match with a @ wild card for a letter
1274 fn = key_handlers[key]
1275 if fn then
1276 -- split off the trailing letter
1277 magic = arg:match("-(%a)$")
1280 if not fn then
1281 -- everything else failed, try default match
1282 fn = key_handlers["*"]
1284 if fn then
1285 local r, err = pcall (fn, arg, magic)
1286 if not r then
1287 log ("WARNING: " .. tostring(err))
1290 end,
1292 -- mouse handling on the lbar
1293 LeftBarClick = function (ev, arg)
1294 local button,tag = string.match(arg, "(%w+)%s+(%S+)")
1295 set_view (tag)
1296 end,
1298 -- focus updates
1299 ClientFocus = function (ev, arg)
1300 log ("ClientFocus: " .. arg)
1301 client_focused (arg)
1302 end,
1303 ColumnFocus = function (ev, arg)
1304 log ("ColumnFocus: " .. arg)
1305 end,
1307 -- client handling
1308 CreateClient = function (ev, arg)
1309 if next_client_goes_to_tag then
1310 local tag = next_client_goes_to_tag
1311 local cli = arg
1312 next_client_goes_to_tag = nil
1313 write ("/client/" .. cli .. "/tags", tag)
1314 set_view(tag)
1316 client_created (arg)
1317 end,
1318 DestroyClient = function (ev, arg)
1319 client_destoryed (arg)
1320 end,
1322 -- urgent tag
1323 UrgentTag = function (ev, arg)
1324 log ("UrgentTag: " .. arg)
1325 write ("/lbar/" .. arg, "*" .. arg);
1326 end,
1327 NotUrgentTag = function (ev, arg)
1328 log ("NotUrgentTag: " .. arg)
1329 write ("/lbar/" .. arg, arg);
1330 end,
1332 -- notifications
1333 Unresponsive = function (ev, arg)
1334 log ("Unresponsive: " .. arg)
1335 -- TODO ask the user if it shoudl be killed off
1336 end,
1338 Notice = function (ev, arg)
1339 log ("Notice: " .. arg)
1340 -- TODO send to the message plugin (or implement there)
1341 end,
1343 -- /
1346 --[[
1347 =pod
1349 =item add_widget_event_handler (wname, ev, fn)
1351 Add an event handler callback for the I<ev> event on the widget named I<wname>
1353 =cut
1354 --]]
1356 function add_widget_event_handler (wname, ev, fn)
1357 if type(wname) ~= "string" or type(ev) ~= "string" or type(fn) ~= "function" then
1358 error ("expecting string for widget name, string for event name and a function callback")
1361 -- Make sure the widget event handler is present
1362 if not ev_handlers[ev] then
1363 ev_handlers[ev] = _handle_widget_event
1366 if not widget_ev_handlers[wname] then
1367 widget_ev_handlers[wname] = { }
1370 if widget_ev_handlers[wname][ev] then
1371 -- TODO: we may wish to allow multiple handlers for one event
1372 error ("event handler already exists on widget '" .. wname .. "' for '" .. ev .. "'")
1375 widget_ev_handlers[wname][ev] = fn
1378 --[[
1379 =pod
1381 =item remove_widget_event_handler (wname, ev)
1383 Remove an event handler callback function for the I<ev> on the widget named I<wname>.
1385 =cut
1386 --]]
1387 function remove_event_handler (wname, ev)
1389 if not widget_ev_handlers[wname] then
1390 return
1393 widget_ev_handlers[wname][ev] = nil
1396 --[[
1397 =pod
1399 =item add_event_handler (ev, fn)
1401 Add an event handler callback function, I<fn>, for the given event I<ev>.
1403 =cut
1404 --]]
1405 -- TODO: Need to allow registering widgets for RightBar* events. Should probably be done with its own event table, though
1406 function add_event_handler (ev, fn)
1407 if type(ev) ~= "string" or type(fn) ~= "function" then
1408 error ("expecting a string and a function")
1411 if ev_handlers[ev] then
1412 -- TODO: we may wish to allow multiple handlers for one event
1413 error ("event handler already exists for '" .. ev .. "'")
1417 ev_handlers[ev] = fn
1420 --[[
1421 =pod
1423 =item remove_event_handler (ev)
1425 Remove an event handler callback function for the given event I<ev>.
1427 =cut
1428 --]]
1429 function remove_event_handler (ev)
1431 ev_handlers[ev] = nil
1435 -- ========================================================================
1436 -- MAIN INTERFACE FUNCTIONS
1437 -- ========================================================================
1439 local config = {
1440 xterm = 'x-terminal-emulator',
1441 xlock = "xscreensaver-command --lock",
1442 debug = false,
1445 -- ------------------------------------------------------------------------
1446 -- write configuration to /ctl wmii file
1447 -- wmii.set_ctl({ "var" = "val", ...})
1448 -- wmii.set_ctl("var, "val")
1449 function set_ctl (first,second)
1450 if type(first) == "table" and second == nil then
1451 local x, y
1452 for x, y in pairs(first) do
1453 write ("/ctl", x .. " " .. y)
1456 elseif type(first) == "string" and type(second) == "string" then
1457 write ("/ctl", first .. " " .. second)
1459 else
1460 error ("expecting a table or two string arguments")
1464 -- ------------------------------------------------------------------------
1465 -- read a value from /ctl wmii file
1466 -- table = wmii.get_ctl()
1467 -- value = wmii.get_ctl("variable")
1468 function get_ctl (name)
1469 local s
1470 local t = {}
1471 for s in iread("/ctl") do
1472 local var,val = s:match("(%w+)%s+(.+)")
1473 if var == name then
1474 return val
1476 t[var] = val
1478 if not name then
1479 return t
1481 return nil
1484 -- ------------------------------------------------------------------------
1485 -- write configuration to /screen/*/ctl wmii file
1486 -- wmii.set_screen_ctl("screen", { "var" = "val", ...})
1487 -- wmii.set_screen_ctl("screen", "var, "val")
1488 function set_screen_ctl (screen, first, second)
1489 local ctl = "/screen/" .. tostring(screen) .. "/ctl"
1490 if not screen then
1491 error ("screen is not set")
1492 elseif type(first) == "table" and second == nil then
1493 local x, y
1494 for x, y in pairs(first) do
1495 write (ctl, x .. " " .. y)
1498 elseif type(first) == "string" and type(second) == "string" then
1499 write (ctl, first .. " " .. second)
1501 else
1502 error ("expecting a screen name, followed by a table or two string arguments")
1506 -- ------------------------------------------------------------------------
1507 -- read a value from /screen/*/ctl wmii file
1508 -- table = wmii.get_screen_ctl("screen")
1509 -- value = wmii.get_screen_ctl("screen", "variable")
1510 function get_screen_ctl (screen, name)
1511 local s
1512 local t = {}
1513 if not screen then
1514 return nil
1516 local ctl = "/screen/" .. tostring(screen) .. "/ctl"
1517 for s in iread(ctl) do
1518 local var,val = s:match("(%w+)%s+(.+)")
1519 if var == name then
1520 return val
1522 -- sometimes first line is the name of the entry
1523 -- in which case there will be no space
1524 t[var or ""] = val
1526 if not name then
1527 return t
1529 return nil
1532 -- ------------------------------------------------------------------------
1533 -- set an internal wmiirc.lua variable
1534 -- wmii.set_conf({ "var" = "val", ...})
1535 -- wmii.set_conf("var, "val")
1536 function set_conf (first,second)
1537 if type(first) == "table" and second == nil then
1538 local x, y
1539 for x, y in pairs(first) do
1540 config[x] = y
1543 elseif type(first) == "string"
1544 and (type(second) == "string"
1545 or type(second) == "number"
1546 or type(second) == "boolean") then
1547 config[first] = second
1549 else
1550 error ("expecting a table, or string and string/number as arguments")
1554 -- ------------------------------------------------------------------------
1555 -- read an internal wmiirc.lua variable
1556 function get_conf (name)
1557 if name then
1558 return config[name]
1560 return config
1563 -- ========================================================================
1564 -- THE EVENT LOOP
1565 -- ========================================================================
1567 -- the event loop instance
1568 local el = eventloop.new()
1569 local event_read_fd = -1
1570 local wmiirc_running = false
1571 local event_read_start = 0
1573 -- ------------------------------------------------------------------------
1574 -- start/restart the core event reading process
1575 local function start_event_reader ()
1576 -- prevent adding two readers
1577 if event_read_fd ~= -1 then
1578 if el:check_exec(event_read_fd) then
1579 return
1582 -- prevert rapid restarts
1583 local now = os.time()
1584 if os.difftime(now, event_read_start) < 5 then
1585 log("wmii: detected rapid restart of /event reader")
1586 local cmd = "wmiir ls /ctl"
1587 if os.execute(cmd) ~= 0 then
1588 log("wmii: cannot confirm communication with wmii, shutting down!")
1589 wmiirc_running = false
1590 return
1592 log("wmii: but things look ok, so we will restart it")
1594 event_read_start = now
1596 -- start a new event reader
1597 log("wmii: starting /event reading process")
1598 event_read_fd = el:add_exec (wmiir .. " read /event",
1599 function (line)
1600 local line = line or "nil"
1602 -- try to split off the argument(s)
1603 local ev,arg = string.match(line, "(%S+)%s+(.+)")
1604 if not ev then
1605 ev = line
1608 -- now locate the handler function and call it
1609 local fn = ev_handlers[ev] or ev_handlers["*"]
1610 if fn then
1611 local r, err = pcall (fn, ev, arg)
1612 if not r then
1613 log ("WARNING: " .. tostring(err))
1618 log("wmii: ... fd=" .. tostring(event_read_fd))
1621 -- ------------------------------------------------------------------------
1622 -- run the event loop and process events, this function does not exit
1623 function run_event_loop ()
1624 -- stop any other instance of wmiirc
1625 wmixp:write ("/event", "Start wmiirc " .. tostring(myid))
1627 log("wmii: updating lbar")
1629 update_displayed_tags ()
1631 log("wmii: updating rbar")
1633 update_displayed_widgets ()
1635 log("wmii: updating active keys")
1637 update_active_keys ()
1639 log("wmii: starting event loop")
1640 wmiirc_running = true
1641 while wmiirc_running do
1642 start_event_reader()
1643 local sleep_for = process_timers()
1644 el:run_loop(sleep_for)
1646 log ("wmii: exiting")
1649 -- ========================================================================
1650 -- PLUGINS API
1651 -- ========================================================================
1653 api_version = 0.1 -- the API version we export
1655 plugins = {} -- all plugins that were loaded
1657 -- ------------------------------------------------------------------------
1658 -- plugin loader which also verifies the version of the api the plugin needs
1660 -- here is what it does
1661 -- - does a manual locate on the file using package.path
1662 -- - reads in the file w/o using the lua interpreter
1663 -- - locates api_version=X.Y string
1664 -- - makes sure that api_version requested can be satisfied
1665 -- - if the plugins is available it will set variables passed in
1666 -- - it then loads the plugin
1668 -- TODO: currently the api_version must be in an X.Y format, but we may want
1669 -- to expend this so plugins can say they want '0.1 | 1.3 | 2.0' etc
1671 function load_plugin(name, vars)
1672 local backup_path = package.path or "./?.lua"
1674 log ("loading " .. name)
1676 -- this is the version we want to find
1677 local api_major, api_minor = tostring(api_version):match("(%d+)%.0*(%d+)")
1678 if (not api_major) or (not api_minor) then
1679 log ("WARNING: could not parse api_version in core/wmii.lua")
1680 return nil
1683 -- first find the plugin file
1684 local s, path_match, full_name, file
1685 for s in string.gmatch(plugin_path, "[^;]+") do
1686 -- try to locate the files locally
1687 local fn = s:gsub("%?", name)
1688 file = io.open(fn, "r")
1689 if file then
1690 path_match = s
1691 full_name = fn
1692 break
1696 -- read it in
1697 local txt
1698 if file then
1699 txt = file:read("*all")
1700 file:close()
1703 if not txt then
1704 log ("WARNING: could not load plugin '" .. name .. "'")
1705 return nil
1708 -- find the api_version line
1709 local line, plugin_version
1710 for line in string.gmatch(txt, "%s*api_version%s*=%s*%d+%.%d+%s*") do
1711 plugin_version = line:match("api_version%s*=%s*(%d+%.%d+)%s*")
1712 if plugin_version then
1713 break
1717 if not plugin_version then
1718 log ("WARNING: could not find api_version string in plugin '" .. name .. "'")
1719 return nil
1722 -- decompose the version string
1723 local plugin_major, plugin_minor = plugin_version:match("(%d+)%.0*(%d+)")
1724 if (not plugin_major) or (not plugin_minor) then
1725 log ("WARNING: could not parse api_version for '" .. name .. "' plugin")
1726 return nil
1729 -- make a version test
1730 if plugin_major ~= api_major then
1731 log ("WARNING: " .. name .. " plugin major version missmatch, is " .. plugin_version
1732 .. " (api " .. tonumber(api_version) .. ")")
1733 return nil
1736 if plugin_minor > api_minor then
1737 log ("WARNING: '" .. name .. "' plugin minor version missmatch, is " .. plugin_version
1738 .. " (api " .. tonumber(api_version) .. ")")
1739 return nil
1742 -- the configuration parameters before loading
1743 if type(vars) == "table" then
1744 local var, val
1745 for var,val in pairs(vars) do
1746 local success = pcall (set_conf, name .. "." .. var, val)
1747 if not success then
1748 log ("WARNING: bad variable {" .. tostring(var) .. ", " .. tostring(val) .. "} "
1749 .. "given; loading '" .. name .. "' plugin failed.")
1750 return nil
1755 -- actually load the module, but use only the path where we though it should be
1756 package.path = path_match
1757 local success,what = pcall (require, name)
1758 package.path = backup_path
1759 if not success then
1760 log ("WARNING: failed to load '" .. name .. "' plugin")
1761 log (" - path: " .. tostring(path_match))
1762 log (" - file: " .. tostring(full_name))
1763 log (" - plugin's api_version: " .. tostring(plugin_version))
1764 log (" - reason: " .. tostring(what))
1765 return nil
1768 -- success
1769 log ("OK, plugin " .. name .. " loaded, requested api v" .. plugin_version)
1770 plugins[name] = what
1771 return what
1774 -- ------------------------------------------------------------------------
1775 -- widget template
1776 widget = {}
1777 widgets = {}
1779 -- ------------------------------------------------------------------------
1780 -- create a widget object and add it to the wmii /rbar
1782 -- examples:
1783 -- widget = wmii.widget:new ("999_clock")
1784 -- widget = wmii.widget:new ("999_clock", clock_event_handler)
1785 function widget:new (name, fn)
1786 local o = {}
1788 if type(name) == "string" then
1789 o.name = name
1790 if type(fn) == "function" then
1791 o.fn = fn
1793 else
1794 error ("expected name followed by an optional function as arguments")
1797 setmetatable (o,self)
1798 self.__index = self
1799 self.__gc = function (o) o:hide() end
1801 widgets[name] = o
1803 o:show()
1804 return o
1807 -- ------------------------------------------------------------------------
1808 -- stop and destroy the timer
1809 function widget:delete ()
1810 widgets[self.name] = nil
1811 self:hide()
1814 -- ------------------------------------------------------------------------
1815 -- displays or updates the widget text
1817 -- examples:
1818 -- w:show("foo")
1819 -- w:show("foo", "#888888 #222222 #333333")
1820 -- w:show("foo", cell_fg .. " " .. cell_bg .. " " .. border)
1822 function widget:show (txt, colors)
1823 local colors = colors or get_ctl("normcolors") or ""
1824 local txt = txt or self.txt or ""
1825 local towrite = txt
1826 if colors then
1827 towrite = colors .. " " .. towrite
1829 if not self.txt then
1830 create ("/rbar/" .. self.name, towrite)
1831 else
1832 write ("/rbar/" .. self.name, towrite)
1834 self.txt = txt
1837 -- ------------------------------------------------------------------------
1838 -- hides a widget and removes it from the bar
1839 function widget:hide ()
1840 if self.txt then
1841 remove ("/lbar/" .. self.name)
1842 self.txt = nil
1846 --[[
1847 =pod
1849 =item widget:add_event_handler (ev, fn)
1851 Add an event handler callback for this widget, using I<fn> for event I<ev>
1853 =cut
1854 --]]
1856 function widget:add_event_handler (ev, fn)
1857 add_widget_event_handler( self.name, ev, fn)
1861 -- ------------------------------------------------------------------------
1862 -- remove all /rbar entries that we don't have widget objects for
1863 function update_displayed_widgets ()
1864 -- colours for /rbar
1865 local nc = get_ctl("normcolors") or ""
1867 -- build up a table of existing tags in the /lbar
1868 local old = {}
1869 local s
1870 for s in wmixp:idir ("/rbar") do
1871 old[s.name] = 1
1874 -- for all actual widgets in use we want to remove them from the old list
1875 local i,v
1876 for i,v in pairs(widgets) do
1877 old[v.name] = nil
1880 -- anything left in the old table should be removed now
1881 for i,v in pairs(old) do
1882 if v then
1883 remove("/rbar/"..i)
1888 -- ------------------------------------------------------------------------
1889 -- create a new program and for each line it generates call the callback function
1890 -- returns fd which can be passed to kill_exec()
1891 function add_exec (command, callback)
1892 return el:add_exec (command, callback)
1895 -- ------------------------------------------------------------------------
1896 -- terminates a program spawned off by add_exec()
1897 function kill_exec (fd)
1898 return el:kill_exec (fd)
1901 -- ------------------------------------------------------------------------
1902 -- timer template
1903 timer = {}
1904 local timers = {}
1906 -- ------------------------------------------------------------------------
1907 -- create a timer object and add it to the event loop
1909 -- examples:
1910 -- timer:new (my_timer_fn)
1911 -- timer:new (my_timer_fn, 15)
1912 function timer:new (fn, seconds)
1913 local o = {}
1915 if type(fn) == "function" then
1916 o.fn = fn
1917 else
1918 error ("expected function followed by an optional number as arguments")
1921 setmetatable (o,self)
1922 self.__index = self
1923 self.__gc = function (o) o:stop() end
1925 -- add the timer
1926 timers[#timers+1] = o
1928 if seconds then
1929 o:resched(seconds)
1931 return o
1934 -- ------------------------------------------------------------------------
1935 -- stop and destroy the timer
1936 function timer:delete ()
1937 self:stop()
1938 local i,t
1939 for i,t in pairs(timers) do
1940 if t == self then
1941 table.remove (timers,i)
1942 return
1947 -- ------------------------------------------------------------------------
1948 -- run the timer given new interval
1949 function timer:resched (seconds)
1950 local seconds = seconds or self.interval
1951 if not (type(seconds) == "number") then
1952 error ("timer:resched expected number as argument")
1955 local now = tonumber(os.date("%s"))
1957 self.interval = seconds
1958 self.next_time = now + seconds
1960 -- resort the timer list
1961 table.sort (timers, timer.is_less_then)
1964 -- helper for sorting timers
1965 function timer:is_less_then(another)
1966 if not self.next_time then
1967 return false -- another is smaller, nil means infinity
1969 elseif not another.next_time then
1970 return true -- self is smaller, nil means infinity
1972 elseif self.next_time < another.next_time then
1973 return true -- self is smaller than another
1976 return false -- another is smaller then self
1979 -- ------------------------------------------------------------------------
1980 -- stop the timer
1981 function timer:stop ()
1982 self.next_time = nil
1984 -- resort the timer list
1985 table.sort (timers, timer.is_less_then)
1988 -- ------------------------------------------------------------------------
1989 -- figure out how long before the next event
1990 function time_before_next_timer_event()
1991 local tmr = timers[1]
1992 if tmr and tmr.next_time then
1993 local now = tonumber(os.date("%s"))
1994 local seconds = tmr.next_time - now
1995 if seconds > 0 then
1996 return seconds
1999 return 0 -- sleep for ever
2002 -- ------------------------------------------------------------------------
2003 -- handle outstanding events
2004 function process_timers ()
2005 local now = tonumber(os.date("%s"))
2006 local torun = {}
2007 local i,tmr
2009 for i,tmr in pairs (timers) do
2010 if not tmr then
2011 -- prune out removed timers
2012 table.remove(timers,i)
2013 break
2015 elseif not tmr.next_time then
2016 -- break out once we find a timer that is stopped
2017 break
2019 elseif tmr.next_time > now then
2020 -- break out once we get to the future
2021 break
2024 -- this one is good to go
2025 torun[#torun+1] = tmr
2028 for i,tmr in pairs (torun) do
2029 tmr:stop()
2030 local status,new_interval = pcall (tmr.fn, tmr)
2031 if status then
2032 new_interval = new_interval or self.interval
2033 if new_interval and (new_interval ~= -1) then
2034 tmr:resched(new_interval)
2036 else
2037 log ("ERROR: " .. tostring(new_interval))
2041 local sleep_for = time_before_next_timer_event()
2042 return sleep_for
2045 -- ------------------------------------------------------------------------
2046 -- cleanup everything in preparation for exit() or exec()
2047 function cleanup ()
2049 local i,v,tmr,p
2051 log ("wmii: stopping timer events")
2053 for i,tmr in pairs (timers) do
2054 pcall (tmr.delete, tmr)
2056 timers = {}
2058 log ("wmii: terminating eventloop")
2060 pcall(el.kill_all,el)
2062 log ("wmii: disposing of widgets")
2064 -- dispose of all widgets
2065 for i,v in pairs(widgets) do
2066 pcall(v.delete,v)
2068 timers = {}
2070 -- FIXME: it doesn't seem to do what I want
2071 --[[
2072 log ("wmii: releasing plugins")
2074 for i,p in pairs(plugins) do
2075 if p.cleanup then
2076 pcall (p.cleanup, p)
2079 plugins = {}
2080 --]]
2082 log ("wmii: dormant")
2083 wmiirc_running = false
2086 -- ========================================================================
2087 -- CLIENT HANDLING
2088 -- ========================================================================
2090 --[[
2091 -- Notes on client tracking
2093 -- When a client is created wmii sends us a CreateClient message, and
2094 -- we in turn create a 'client' object and store it in the 'clients'
2095 -- table indexed by the client's ID.
2097 -- Each client object stores the following:
2098 -- .xid - the X client ID
2099 -- .pid - the process ID
2100 -- .prog - program object representing the process
2102 -- The client and program objects track the following modes for each program:
2104 -- raw mode:
2105 -- - for each client window
2106 -- - Mod4-space toggles the state between normal and raw
2107 -- - Mod1-f raw also toggles the state
2108 -- - in raw mode all input goes to the client, except for Mod4-space
2109 -- - a focused client with raw mode enabled is put into raw mode
2111 -- suspend mode:
2112 -- - for each program
2113 -- - Mod1-f suspend toggles the state for current client's program
2114 -- - a focused client, whose program was previous suspended is resumed
2115 -- - an unfocused client, with suspend enabled, will be suspended
2116 -- - suspend/resume is done by sending the STOP/CONT signals to the PID
2117 --]]
2119 function xid_to_pid (xid)
2120 local cmd = "xprop -id " .. tostring(xid) .. " _NET_WM_PID"
2121 local file = io.popen (cmd)
2122 local out = file:read("*a")
2123 file:close()
2124 local pid = out:match("^_NET_WM_PID.*%s+=%s+(%d+)%s+$")
2125 return tonumber(pid)
2128 local focused_xid = nil
2129 local clients = {} -- table of client objects indexed by xid
2130 local programs = {} -- table of program objects indexed by pid
2131 local mode_widget = widget:new ("999_client_mode")
2133 -- make programs table have weak values
2134 -- programs go away as soon as no clients point to it
2135 local programs_mt = {}
2136 setmetatable(programs, programs_mt)
2137 programs_mt.__mode = 'v'
2139 -- program class
2140 program = {}
2141 function program:new (pid)
2142 -- make an object
2143 local o = {}
2144 setmetatable (o,self)
2145 self.__index = self
2146 self.__gc = function (old) old:cont() end
2147 -- initialize the new object
2148 o.pid = pid
2149 -- suspend mode
2150 o.suspend = {}
2151 o.suspend.toggle = function (prog)
2152 prog.suspend.enabled = not prog.suspend.enabled
2154 o.suspend.enabled = false -- if true, defocusing suspends (SIGSTOP)
2155 o.suspend.active = true -- if true, focusing resumes (SIGCONT)
2156 return o
2159 function program:stop ()
2160 if not self.suspend.active then
2161 local cmd = "kill -STOP " .. tostring(self.pid)
2162 log (" executing: " .. cmd)
2163 os.execute (cmd)
2164 self.suspend.active = true
2168 function program:cont ()
2169 if self.suspend.active then
2170 local cmd = "kill -CONT " .. tostring(self.pid)
2171 log (" executing: " .. cmd)
2172 os.execute (cmd)
2173 self.suspend.active = false
2177 function get_program (pid)
2178 local prog = programs[pid]
2179 if pid and not prog then
2180 prog = program:new (pid)
2181 programs[pid] = prog
2183 return prog
2186 -- client class
2187 client = {}
2188 function client:new (xid)
2189 local pid = xid_to_pid(xid)
2190 if not pid then
2191 log ("WARNING: failed to convert XID " .. tostring(xid) .. " to a PID")
2192 return
2194 -- make an object
2195 local o = {}
2196 setmetatable (o,self)
2197 self.__index = function (t,k)
2198 if k == 'suspend' then -- suspend mode is tracked per program
2199 return t.prog.suspend
2201 return self[k]
2203 self.__gc = function (old) old.prog=nil end
2204 -- initialize the new object
2205 o.xid = xid
2206 o.pid = pid
2207 o.prog = get_program (pid)
2208 -- raw mode
2209 o.raw = {}
2210 o.raw.toggle = function (cli)
2211 cli.raw.enabled = not cli.raw.enabled
2212 cli:set_raw_mode()
2214 o.raw.enabled = false -- if true, raw mode enabled when client is focused
2215 return o
2218 function client:stop ()
2219 if self.suspend.enabled then
2220 self.prog:stop()
2224 function client:cont ()
2225 self.prog:cont()
2228 function client:set_raw_mode()
2229 if not self or not self.raw.enabled then -- normal mode
2230 update_active_keys ()
2231 else -- raw mode
2232 write ("/keys", "Mod4-space")
2236 function client:toggle(what)
2237 if what and self[what] then
2238 local ctl = self[what]
2240 ctl.toggle (self)
2242 log ("xid=" .. tostring (xid)
2243 .. " pid=" .. tostring (self.pid) .. " (" .. tostring (self.prog.pid) .. ")"
2244 .. " what=" .. tostring (what)
2245 .. " enabled=" .. tostring(ctl["enabled"]))
2247 mode_widget:show (self:flags_string())
2250 function client:flags_string()
2251 local ret = ''
2252 if self.suspend.enabled then ret = ret .. "s" else ret = ret .. "-" end
2253 if self.raw.enabled then ret = ret .. "r" else ret = ret .. "-" end
2254 return ret
2257 function get_client (xid)
2258 local xid = xid or wmixp:read("/client/sel/ctl")
2259 local cli = clients[xid]
2260 if not cli then
2261 cli = client:new (xid)
2262 clients[xid] = cli
2264 return cli
2267 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
2268 function client_created (xid)
2269 log ("-client_created " .. tostring(xid))
2270 return get_client(xid)
2273 function client_destoryed (xid)
2274 log ("-client_destoryed " .. tostring(xid))
2275 if clients[xid] then
2276 local cli = clients[xid]
2277 clients[xid] = nil
2278 log (" del pid: " .. tostring(cli.pid))
2279 cli:cont()
2281 if focused_xid == xid then
2282 focused_xid = nil
2286 function client_focused (xid)
2287 log ("-client_focused " .. tostring(xid))
2288 -- return the current focused xid if nil is passed
2289 if type(xid) ~= 'string' or not xid:match("0x%x*$") then
2290 return focused_xid
2292 -- do nothing if the same xid
2293 if focused_xid == xid then
2294 return clients[xid]
2297 local old = clients[focused_xid]
2298 local new = get_client(xid)
2300 -- handle raw mode switch
2301 if not old or ( old and new and old.raw.enabled ~= new.raw.enabled ) then
2302 new:set_raw_mode()
2305 -- do nothing if the same pid
2306 if old and new and old.pid == new.pid then
2307 mode_widget:show (new:flags_string())
2308 return clients[xid]
2311 if old then
2312 --[[
2313 log (" old pid: " .. tostring(old.pid)
2314 .. " xid: " .. tostring(old.xid)
2315 .. " flags: " .. old:flags_string())
2316 ]]--
2317 old:stop()
2320 if new then
2321 --[[
2322 log (" new pid: " .. tostring(new.pid)
2323 .. " xid: " .. tostring(new.xid)
2324 .. " flags: " .. new:flags_string())
2325 ]]--
2326 new:cont()
2329 mode_widget:show (new:flags_string())
2330 focused_xid = xid
2331 return new
2335 -- ========================================================================
2336 -- DOCUMENTATION
2337 -- ========================================================================
2339 --[[
2340 =pod
2342 =back
2344 =head1 ENVIRONMENT
2346 =over 4
2348 =item WMII_ADDRESS
2350 Used to determine location of wmii's listen socket.
2352 =back
2354 =head1 SEE ALSO
2356 L<wmii(1)>, L<lua(1)>
2358 =head1 AUTHOR
2360 Bart Trojanowski B<< <bart@jukie.net> >>
2362 =head1 COPYRIGHT AND LICENSE
2364 Copyright (c) 2007, Bart Trojanowski <bart@jukie.net>
2366 This is free software. You may redistribute copies of it under the terms of
2367 the GNU General Public License L<http://www.gnu.org/licenses/gpl.html>. There
2368 is NO WARRANTY, to the extent permitted by law.
2370 =cut
2371 --]]