convert old usage of mypid in core/wmii.lua to myid
[wmiirc-lua.git] / core / wmii.lua
blobea4388fd9be2ca64d5345dbb6b5008c41110c58e
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 = os.getenv("HOME") .. "/.wmii-3.5"
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 myid = posix.getprocessid("pid")
98 else
99 local now = tonumber(os.date("%s"))
100 math.randomseed(now)
101 myid = math.random(10000)
104 -- ========================================================================
105 -- MODULE VARIABLES
106 -- ========================================================================
108 -- wmiir points to the wmiir executable
109 -- TODO: need to make sure that wmiir is in path, and if not find it
110 local wmiir = "wmiir"
112 -- wmii_adr is the address we use when connecting using ixp
113 local wmii_adr = os.getenv("WMII_ADDRESS")
114 or ("unix!/tmp/ns." .. os.getenv("USER") .. "."
115 .. os.getenv("DISPLAY"):match("(:%d+)") .. "/wmii")
117 -- wmixp is the ixp context we use to talk to wmii
118 local wmixp = ixp.new(wmii_adr)
120 -- history of previous views, view_hist[#view_hist] is the last one
121 local view_hist = {} -- sorted with 1 being the oldest
122 local view_hist_max = 50 -- max number to keep track of
124 -- allow for a client to be forced to a tag
125 local next_client_goes_to_tag = nil
127 -- program and action histories
128 local prog_hist = history.new (20)
129 local action_hist = history.new(10)
131 -- where to find plugins
132 plugin_path = os.getenv("HOME") .. "/.wmii-3.5/plugins/?.so;"
133 .. os.getenv("HOME") .. "/.wmii-3.5/plugins/?.lua;"
134 .. "/usr/local/lib/lua/5.1/wmii/?.so;"
135 .. "/usr/local/share/lua/5.1/wmii/?.lua;"
136 .. "/usr/lib/lua/5.1/wmii/?.so;"
137 .. "/usr/share/lua/5.1/wmii/?.lua"
139 -- where to find wmiirc (see find_wmiirc())
140 wmiirc_path = os.getenv("HOME") .. "/.wmii-3.5/wmiirc.lua;"
141 .. os.getenv("HOME") .. "/.wmii-3.5/wmiirc;"
142 .. "/etc/X11/wmii-3.5/wmiirc.lua;"
143 .. "/etc/X11/wmii-3.5/wmiirc"
145 -- ========================================================================
146 -- LOCAL HELPERS
147 -- ========================================================================
149 --[[
150 =pod
152 =item log ( str )
154 Log the message provided in C<str>
156 Currently just writes to io.stderr
158 =cut
159 --]]
160 function log (str)
161 if get_conf("debug") then
162 io.stderr:write (str .. "\n")
166 --[[
167 =pod
169 =item find_wmiirc ( )
171 Locates the wmiirc script. It looks in ~/.wmii-3.5 and /etc/X11/wmii-3.5
172 for the first lua script bearing the name wmiirc.lua or wmiirc. Returns
173 first match.
175 =cut
176 --]]
177 function find_wmiirc()
178 local fn
179 for fn in string.gmatch(wmiirc_path, "[^;]+") do
180 -- try to locate the files locally
181 local file = io.open(fn, "r")
182 if file then
183 local txt = file:read("*line")
184 file:close()
185 if type(txt) == 'string' and txt:match("lua") then
186 return fn
190 return nil
194 -- ========================================================================
195 -- MAIN ACCESS FUNCTIONS
196 -- ========================================================================
198 --[[
199 =pod
201 =item ls ( dir, fmt )
203 List the wmii filesystem directory provided in C<dir>, in the format specified
204 by C<fmt>.
206 Returns an iterator of TODO
208 =cut
209 --]]
210 function ls (dir, fmt)
211 local verbose = fmt and fmt:match("l")
213 local s = wmixp:stat(dir)
214 if not s then
215 return function () return nil end
217 if s.modestr:match("^[^d]") then
218 return function ()
219 return stat2str(verbose, s)
223 local itr = wmixp:idir (dir)
224 if not itr then
225 --return function ()
226 return nil
227 --end
231 return function ()
232 local s = itr()
233 if s then
234 return stat2str(verbose, s)
236 return nil
240 local function stat2str(verbose, stat)
241 if verbose then
242 return string.format("%s %s %s %5d %s %s", stat.modestr, stat.uid, stat.gid, stat.length, stat.timestr, stat.name)
243 else
244 if stat.modestr:match("^d") then
245 return stat.name .. "/"
246 else
247 return stat.name
252 -- ------------------------------------------------------------------------
253 -- read all contents of a wmii virtual file
254 function read (file)
255 return wmixp:read (file)
258 -- ------------------------------------------------------------------------
259 -- return an iterator which walks all the lines in the file
261 -- example:
262 -- for event in wmii.iread("/ctl")
263 -- ...
264 -- end
266 -- NOTE: don't use iread for files that could block, as this will interfere
267 -- with timer processing and event delivery. Instead fork off a process to
268 -- execute wmiir and read back the responses via callback.
269 function iread (file)
270 return wmixp:iread(file)
273 -- ------------------------------------------------------------------------
274 -- create a wmii file, optionally write data to it
275 function create (file, data)
276 wmixp:create(file, data)
279 -- ------------------------------------------------------------------------
280 -- remove a wmii file
281 function remove (file)
282 wmixp:remove(file)
285 -- ------------------------------------------------------------------------
286 -- write a value to a wmii virtual file system
287 function write (file, value)
288 wmixp:write (file, value)
291 -- ------------------------------------------------------------------------
292 -- setup a table describing dmenu command
293 local function dmenu_cmd (prompt, iterator)
294 local cmdt = { "dmenu", "-b" }
295 local fn = get_ctl("font")
296 if fn then
297 cmdt[#cmdt+1] = "-fn"
298 cmdt[#cmdt+1] = fn
300 local normcolors = get_ctl("normcolors")
301 if normcolors then
302 local nf, nb = normcolors:match("(#%x+)%s+(#%x+)%s#%x+")
303 if nf then
304 cmdt[#cmdt+1] = "-nf"
305 cmdt[#cmdt+1] = "'" .. nf .. "'"
307 if nb then
308 cmdt[#cmdt+1] = "-nb"
309 cmdt[#cmdt+1] = "'" .. nb .. "'"
312 local focuscolors = get_ctl("focuscolors")
313 if focuscolors then
314 local sf, sb = focuscolors:match("(#%x+)%s+(#%x+)%s#%x+")
315 if sf then
316 cmdt[#cmdt+1] = "-sf"
317 cmdt[#cmdt+1] = "'" .. sf .. "'"
319 if sb then
320 cmdt[#cmdt+1] = "-sb"
321 cmdt[#cmdt+1] = "'" .. sb .. "'"
324 if prompt then
325 cmdt[#cmdt+1] = "-p"
326 cmdt[#cmdt+1] = "'" .. prompt .. "'"
329 return cmdt
332 -- ------------------------------------------------------------------------
333 -- displays the menu given an table of entires, returns selected text
334 function menu (tbl, prompt)
335 local dmenu = dmenu_cmd(prompt)
337 local infile = os.tmpname()
338 local fh = io.open (infile, "w+")
340 local i,v
341 for i,v in pairs(tbl) do
342 if type(i) == 'number' and type(v) == 'string' then
343 fh:write (v)
344 else
345 fh:write (i)
347 fh:write ("\n")
349 fh:close()
351 local outfile = os.tmpname()
353 dmenu[#dmenu+1] = "<"
354 dmenu[#dmenu+1] = infile
355 dmenu[#dmenu+1] = ">"
356 dmenu[#dmenu+1] = outfile
358 local cmd = table.concat(dmenu," ")
359 os.execute (cmd)
361 fh = io.open (outfile, "r")
362 os.remove (outfile)
364 local sel = fh:read("*l")
365 fh:close()
367 return sel
370 -- ------------------------------------------------------------------------
371 -- displays the a tag selection menu, returns selected tag
372 function tag_menu ()
373 local tags = get_tags()
375 return menu(tags, "tag:")
378 -- ------------------------------------------------------------------------
379 -- displays the a program menu, returns selected program
380 function prog_menu ()
381 local dmenu = dmenu_cmd("cmd:")
383 local outfile = os.tmpname()
385 dmenu[#dmenu+1] = ">"
386 dmenu[#dmenu+1] = outfile
388 local hstt = { }
389 for n in prog_hist:walk_reverse_unique() do
390 hstt[#hstt+1] = "echo '" .. n .. "' ; "
393 local cmd = "(" .. table.concat(hstt)
394 .. "dmenu_path ) |"
395 .. table.concat(dmenu," ")
396 os.execute (cmd)
398 local fh = io.open (outfile, "rb")
399 os.remove (outfile)
401 local prog = fh:read("*l")
402 io.close (fh)
404 return prog
407 -- ------------------------------------------------------------------------
408 -- displays the a program menu, returns selected program
409 function get_tags()
410 local t = {}
411 local s
412 for s in wmixp:idir ("/tag") do
413 if s.name and not (s.name == "sel") then
414 t[#t + 1] = s.name
417 table.sort(t)
418 return t
421 -- ------------------------------------------------------------------------
422 -- displays the a program menu, returns selected program
423 function get_view()
424 local v = wmixp:read("/ctl") or ""
425 return v:match("view%s+(%S+)")
428 -- ------------------------------------------------------------------------
429 -- changes the current view to the name given
430 function set_view(sel)
431 local cur = get_view()
432 local all = get_tags()
434 if #all < 2 or sel == cur then
435 -- nothing to do if we have less then 2 tags
436 return
439 if not (type(sel) == "string") then
440 error ("string argument expected")
443 -- set new view
444 write ("/ctl", "view " .. sel)
447 -- ------------------------------------------------------------------------
448 -- changes the current view to the index given
449 function set_view_index(sel)
450 local cur = get_view()
451 local all = get_tags()
453 if #all < 2 then
454 -- nothing to do if we have less then 2 tags
455 return
458 local num = tonumber (sel)
459 if not num then
460 error ("number argument expected")
463 local name = all[sel]
464 if not name or name == cur then
465 return
468 -- set new view
469 write ("/ctl", "view " .. name)
472 -- ------------------------------------------------------------------------
473 -- chnages to current view by offset given
474 function set_view_ofs(jump)
475 local cur = get_view()
476 local all = get_tags()
478 if #all < 2 then
479 -- nothing to do if we have less then 2 tags
480 return
483 -- range check
484 if (jump < - #all) or (jump > #all) then
485 error ("view selector is out of range")
488 -- find the one that's selected index
489 local curi = nil
490 local i,v
491 for i,v in pairs (all) do
492 if v == cur then curi = i end
495 -- adjust by index
496 local newi = math.fmod(#all + curi + jump - 1, #all) + 1
497 if (newi < - #all) or (newi > #all) then
498 error ("error computng new view")
501 write ("/ctl", "view " .. all[newi])
504 -- ------------------------------------------------------------------------
505 -- toggle between last view and current view
506 function toggle_view()
507 local last = view_hist[#view_hist]
508 if last then
509 set_view(last)
513 -- ========================================================================
514 -- ACTION HANDLERS
515 -- ========================================================================
517 local action_handlers = {
518 man = function (act, args)
519 local xterm = get_conf("xterm") or "xterm"
520 local page = args
521 if (not page) or (not page:match("%S")) then
522 page = wmiidir .. "/wmii.3lua"
524 local cmd = xterm .. " -e man " .. page .. " &"
525 log (" executing: " .. cmd)
526 os.execute (cmd)
527 end,
529 quit = function ()
530 write ("/ctl", "quit")
531 end,
533 exec = function (act, args)
534 local what = args or "wmii"
535 log (" asking wmii to exec " .. tostring(what))
536 cleanup()
537 write ("/ctl", "exec " .. what)
538 end,
540 xlock = function (act)
541 local cmd = get_conf("xlock") or "xscreensaver-command --lock"
542 os.execute (cmd)
543 end,
545 wmiirc = function ()
546 if have_posix then
547 local wmiirc = find_wmiirc()
548 if wmiirc then
549 log (" executing: lua " .. wmiirc)
550 cleanup()
551 posix.exec ("lua", wmiirc)
553 else
554 log("sorry cannot restart; you don't have lua's posix library.")
556 end,
558 --[[
559 rehash = function ()
560 -- TODO: consider storing list of executables around, and
561 -- this will then reinitialize that list
562 log (" TODO: rehash")
563 end,
565 status = function ()
566 -- TODO: this should eventually update something on the /rbar
567 log (" TODO: status")
568 end,
569 --]]
572 --[[
573 =pod
575 =item add_action_handler (action, fn)
577 Add an Alt-a action handler callback function, I<fn>, for the given action string I<action>.
579 =cut
580 --]]
581 function add_action_handler (action, fn)
583 if type(action) ~= "string" or type(fn) ~= "function" then
584 error ("expecting a string and a function")
587 if action_handlers[action] then
588 error ("action handler already exists for '" .. action .. "'")
591 action_handlers[action] = fn
594 --[[
595 =pod
597 =item remove_action_handler (action)
599 Remove an action handler callback function for the given action string I<action>.
601 =cut
602 --]]
603 function remove_action_handler (action)
605 action_handlers[action] = nil
608 -- ========================================================================
609 -- KEY HANDLERS
610 -- ========================================================================
612 function ke_view_starting_with_letter (letter)
613 local i,v
615 -- find the view name in history in reverse order
616 for i=#view_hist,1,-1 do
617 v = view_hist[i]
618 if letter == v:sub(1,1) then
619 set_view(v)
620 return true
624 -- otherwise just pick the first view that matches
625 local all = get_tags()
626 for i,v in pairs(all) do
627 if letter == v:sub(1,1) then
628 set_view_index (i)
629 return true
633 return false
636 function ke_handle_action()
637 local actions = { }
638 local seen = {}
640 local n
641 for n in action_hist:walk_reverse() do
642 if not seen[n] then
643 actions[#actions+1] = n
644 seen[n] = 1
648 local v
649 for n,v in pairs(action_handlers) do
650 if not seen[n] then
651 actions[#actions+1] = n
652 seen[n] = 1
656 local text = menu(actions, "action:")
657 if text then
658 log ("Action: " .. text)
659 local act = text
660 local args = nil
661 local si = text:find("%s")
662 if si then
663 act,args = string.match(text .. " ", "(%w+)%s(.+)")
665 if act then
666 local fn = action_handlers[act]
667 if fn then
668 action_hist:add (act)
669 local r, err = pcall (fn, act, args)
670 if not r then
671 log ("WARNING: " .. tostring(err))
679 local key_handlers = {
680 ["*"] = function (key)
681 log ("*: " .. key)
682 end,
684 -- execution and actions
685 ["Mod1-Return"] = function (key)
686 local xterm = get_conf("xterm") or "xterm"
687 log (" executing: " .. xterm)
688 os.execute (xterm .. " &")
689 end,
690 ["Mod1-Shift-Return"] = function (key)
691 local tag = tag_menu()
692 if tag then
693 local xterm = get_conf("xterm") or "xterm"
694 log (" executing: " .. xterm .. " on: " .. tag)
695 next_client_goes_to_tag = tag
696 os.execute (xterm .. " &")
698 end,
699 ["Mod1-a"] = function (key)
700 ke_handle_action()
701 end,
702 ["Mod1-p"] = function (key)
703 local prog = prog_menu()
704 if prog then
705 prog_hist:add(prog:match("(%w+)"))
706 log (" executing: " .. prog)
707 os.execute (prog .. " &")
709 end,
710 ["Mod1-Shift-p"] = function (key)
711 local tag = tag_menu()
712 if tag then
713 local prog = prog_menu()
714 if prog then
715 log (" executing: " .. prog .. " on: " .. tag)
716 next_client_goes_to_tag = tag
717 os.execute (prog .. " &")
720 end,
721 ["Mod1-Shift-c"] = function (key)
722 write ("/client/sel/ctl", "kill")
723 end,
725 -- HJKL active selection
726 ["Mod1-h"] = function (key)
727 write ("/tag/sel/ctl", "select left")
728 end,
729 ["Mod1-l"] = function (key)
730 write ("/tag/sel/ctl", "select right")
731 end,
732 ["Mod1-j"] = function (key)
733 write ("/tag/sel/ctl", "select down")
734 end,
735 ["Mod1-k"] = function (key)
736 write ("/tag/sel/ctl", "select up")
737 end,
739 -- HJKL movement
740 ["Mod1-Shift-h"] = function (key)
741 write ("/tag/sel/ctl", "send sel left")
742 end,
743 ["Mod1-Shift-l"] = function (key)
744 write ("/tag/sel/ctl", "send sel right")
745 end,
746 ["Mod1-Shift-j"] = function (key)
747 write ("/tag/sel/ctl", "send sel down")
748 end,
749 ["Mod1-Shift-k"] = function (key)
750 write ("/tag/sel/ctl", "send sel up")
751 end,
753 -- floating vs tiled
754 ["Mod1-space"] = function (key)
755 write ("/tag/sel/ctl", "select toggle")
756 end,
757 ["Mod1-Shift-space"] = function (key)
758 write ("/tag/sel/ctl", "send sel toggle")
759 end,
761 -- work spaces (# and @ are wildcards for numbers and letters)
762 ["Mod4-#"] = function (key, num)
763 -- first attempt to find a view that starts with the number requested
764 local num_str = tostring(num)
765 if not ke_view_starting_with_letter (num_str) then
766 -- if we fail, then set it to the index requested
767 set_view_index (num)
769 end,
770 ["Mod4-Shift-#"] = function (key, num)
771 write ("/client/sel/tags", tostring(num))
772 end,
773 ["Mod4-@"] = function (key, letter)
774 ke_view_starting_with_letter (letter)
775 end,
776 ["Mod4-Shift-@"] = function (key, letter)
777 local all = get_tags()
778 local i,v
779 for i,v in pairs(all) do
780 if letter == v:sub(1,1) then
781 write ("/client/sel/tags", v)
782 break
785 end,
786 ["Mod1-comma"] = function (key)
787 set_view_ofs (-1)
788 end,
789 ["Mod1-period"] = function (key)
790 set_view_ofs (1)
791 end,
792 ["Mod1-r"] = function (key)
793 -- got to the last view
794 toggle_view()
795 end,
797 -- switching views and retagging
798 ["Mod1-t"] = function (key)
799 -- got to a view
800 local tag = tag_menu()
801 if tag then
802 set_view (tag)
804 end,
805 ["Mod1-Shift-t"] = function (key)
806 -- move selected client to a tag
807 local tag = tag_menu()
808 if tag then
809 write ("/client/sel/tags", tag)
811 end,
812 ["Mod1-Shift-r"] = function (key)
813 -- move selected client to a tag, and follow
814 local tag = tag_menu()
815 if tag then
816 write ("/client/sel/tags", tag)
817 set_view(tag)
819 end,
820 ["Mod1-Control-t"] = function (key)
821 log (" TODO: Mod1-Control-t: " .. key)
822 end,
824 -- column modes
825 ["Mod1-d"] = function (key)
826 write("/tag/sel/ctl", "colmode sel default")
827 end,
828 ["Mod1-s"] = function (key)
829 write("/tag/sel/ctl", "colmode sel stack")
830 end,
831 ["Mod1-m"] = function (key)
832 write("/tag/sel/ctl", "colmode sel max")
833 end,
835 -- changing client flags
836 ["Mod1-f"] = function (key)
837 log ("setting flags")
839 local cli = get_client ()
841 local flags = { "suspend", "raw" }
842 local current_flags = cli:flags_string()
844 local what = menu(flags, "current flags: " .. current_flags .. " toggle:")
846 cli:toggle(what)
847 end,
848 ["Mod4-space"] = function (key)
849 local cli = get_client ()
850 cli:toggle("raw")
851 end,
854 --[[
855 =pod
857 =item add_key_handler (key, fn)
859 Add a keypress handler callback function, I<fn>, for the given key sequence I<key>.
861 =cut
862 --]]
863 function add_key_handler (key, fn)
865 if type(key) ~= "string" or type(fn) ~= "function" then
866 error ("expecting a string and a function")
869 if key_handlers[key] then
870 -- TODO: we may wish to allow multiple handlers for one keypress
871 error ("key handler already exists for '" .. key .. "'")
874 key_handlers[key] = fn
877 --[[
878 =pod
880 =item remove_key_handler (key)
882 Remove an key handler callback function for the given key I<key>.
884 Returns the handler callback function.
886 =cut
887 --]]
888 function remove_key_handler (key)
890 local fn = key_handlers[key]
891 key_handlers[key] = nil
892 return fn
895 --[[
896 =pod
898 =item remap_key_handler (old_key, new_key)
900 Remove a key handler callback function from the given key I<old_key>,
901 and assign it to a new key I<new_key>.
903 =cut
904 --]]
905 function remap_key_handler (old_key, new_key)
907 local fn = remove_key_handler(old_key)
909 return add_key_handler (new_key, fn)
913 -- ------------------------------------------------------------------------
914 -- update the /keys wmii file with the list of all handlers
915 local alphabet="abcdefghijklmnopqrstuvwxyz"
916 function update_active_keys ()
917 local t = {}
918 local x, y
919 for x,y in pairs(key_handlers) do
920 if x:find("%w") then
921 local i = x:find("#$")
922 if i then
923 local j
924 for j=0,9 do
925 t[#t + 1] = x:sub(1,i-1) .. j
927 else
928 i = x:find("@$")
929 if i then
930 local j
931 for j=1,alphabet:len() do
932 local a = alphabet:sub(j,j)
933 t[#t + 1] = x:sub(1,i-1) .. a
935 else
936 t[#t + 1] = tostring(x)
941 local all_keys = table.concat(t, "\n")
942 --log ("setting /keys to...\n" .. all_keys .. "\n");
943 write ("/keys", all_keys)
946 -- ------------------------------------------------------------------------
947 -- update the /lbar wmii file with the current tags
948 function update_displayed_tags ()
949 -- colours for /lbar
950 local fc = get_ctl("focuscolors") or ""
951 local nc = get_ctl("normcolors") or ""
953 -- build up a table of existing tags in the /lbar
954 local old = {}
955 local s
956 for s in wmixp:idir ("/lbar") do
957 old[s.name] = 1
960 -- for all actual tags in use create any entries in /lbar we don't have
961 -- clear the old table entries if we have them
962 local cur = get_view()
963 local all = get_tags()
964 local i,v
965 for i,v in pairs(all) do
966 local color = nc
967 if cur == v then
968 color = fc
970 if not old[v] then
971 create ("/lbar/" .. v, color .. " " .. v)
973 write ("/lbar/" .. v, color .. " " .. v)
974 old[v] = nil
977 -- anything left in the old table should be removed now
978 for i,v in pairs(old) do
979 if v then
980 remove("/lbar/"..i)
985 -- ========================================================================
986 -- EVENT HANDLERS
987 -- ========================================================================
989 local widget_ev_handlers = {
992 --[[
993 =pod
995 =item _handle_widget_event (ev, arg)
997 Top-level event handler for redispatching events to widgets. This event
998 handler is added for any widget event that currently has a widget registered
999 for it.
1001 Valid widget events are currently
1003 RightBarMouseDown <buttonnumber> <widgetname>
1004 RightBarClick <buttonnumber> <widgetname>
1006 the "Click" event is sent on mouseup.
1008 The callbacks are given only the button number as their argument, to avoid the
1009 need to reparse.
1011 =cut
1012 --]]
1014 local function _handle_widget_event (ev, arg)
1016 log("_handle_widget_event: " .. tostring(ev) .. " - " .. tostring(arg))
1018 -- parse arg to strip out our widget name
1019 local number,wname = string.match(arg, "(%d+)%s+(.+)")
1021 -- check our dispatch table for that widget
1022 if not wname then
1023 log("Didn't find wname")
1024 return
1027 local wtable = widget_ev_handlers[wname]
1028 if not wtable then
1029 log("No widget cares about" .. wname)
1030 return
1033 local fn = wtable[ev] or wtable["*"]
1034 if fn then
1035 success, err = pcall( fn, ev, tonumber(number) )
1036 if not success then
1037 log("Callback had an error in _handle_widget_event: " .. tostring(err) )
1038 return nil
1040 else
1041 log("no function found for " .. ev)
1045 local ev_handlers = {
1046 ["*"] = function (ev, arg)
1047 log ("ev: " .. tostring(ev) .. " - " .. tostring(arg))
1048 end,
1050 RightBarClick = _handle_widget_event,
1052 -- process timer events
1053 ProcessTimerEvents = function (ev, arg)
1054 process_timers()
1055 end,
1057 -- exit if another wmiirc started up
1058 Start = function (ev, arg)
1059 if arg then
1060 if arg == "wmiirc" then
1061 -- backwards compatibility with bash version
1062 log (" exiting; pid=" .. tostring(myid))
1063 cleanup()
1064 os.exit (0)
1065 else
1066 -- ignore if it came from us
1067 local pid = string.match(arg, "wmiirc (%d+)")
1068 if pid then
1069 local pid = tonumber (pid)
1070 if not (pid == myid) then
1071 log (" exiting; pid=" .. tostring(myid))
1072 cleanup()
1073 os.exit (0)
1078 end,
1080 -- tag management
1081 CreateTag = function (ev, arg)
1082 local nc = get_ctl("normcolors") or ""
1083 create ("/lbar/" .. arg, nc .. " " .. arg)
1084 end,
1085 DestroyTag = function (ev, arg)
1086 remove ("/lbar/" .. arg)
1087 end,
1089 FocusTag = function (ev, arg)
1090 local fc = get_ctl("focuscolors") or ""
1091 create ("/lbar/" .. arg, fc .. " " .. arg)
1092 write ("/lbar/" .. arg, fc .. " " .. arg)
1093 end,
1094 UnfocusTag = function (ev, arg)
1095 local nc = get_ctl("normcolors") or ""
1096 create ("/lbar/" .. arg, nc .. " " .. arg)
1097 write ("/lbar/" .. arg, nc .. " " .. arg)
1099 -- don't duplicate the last entry
1100 if not (arg == view_hist[#view_hist]) then
1101 view_hist[#view_hist+1] = arg
1103 -- limit to view_hist_max
1104 if #view_hist > view_hist_max then
1105 table.remove(view_hist, 1)
1108 end,
1110 -- key event handling
1111 Key = function (ev, arg)
1112 log ("Key: " .. arg)
1113 local magic = nil
1114 -- can we find an exact match?
1115 local fn = key_handlers[arg]
1116 if not fn then
1117 local key = arg:gsub("-%d$", "-#")
1118 -- can we find a match with a # wild card for the number
1119 fn = key_handlers[key]
1120 if fn then
1121 -- convert the trailing number to a number
1122 magic = tonumber(arg:match("-(%d)$"))
1125 if not fn then
1126 local key = arg:gsub("-%a$", "-@")
1127 -- can we find a match with a @ wild card for a letter
1128 fn = key_handlers[key]
1129 if fn then
1130 -- split off the trailing letter
1131 magic = arg:match("-(%a)$")
1134 if not fn then
1135 -- everything else failed, try default match
1136 fn = key_handlers["*"]
1138 if fn then
1139 local r, err = pcall (fn, arg, magic)
1140 if not r then
1141 log ("WARNING: " .. tostring(err))
1144 end,
1146 -- mouse handling on the lbar
1147 LeftBarClick = function (ev, arg)
1148 local button,tag = string.match(arg, "(%w+)%s+(%S+)")
1149 set_view (tag)
1150 end,
1152 -- focus updates
1153 ClientFocus = function (ev, arg)
1154 log ("ClientFocus: " .. arg)
1155 client_focused (arg)
1156 end,
1157 ColumnFocus = function (ev, arg)
1158 log ("ColumnFocus: " .. arg)
1159 end,
1161 -- client handling
1162 CreateClient = function (ev, arg)
1163 if next_client_goes_to_tag then
1164 local tag = next_client_goes_to_tag
1165 local cli = arg
1166 next_client_goes_to_tag = nil
1167 write ("/client/" .. cli .. "/tags", tag)
1168 set_view(tag)
1170 client_created (arg)
1171 end,
1172 DestroyClient = function (ev, arg)
1173 client_destoryed (arg)
1174 end,
1176 -- urgent tag?
1177 UrgentTag = function (ev, arg)
1178 log ("UrgentTag: " .. arg)
1179 -- wmiir xwrite "/lbar/$@" "*$@"
1180 end,
1181 NotUrgentTag = function (ev, arg)
1182 log ("NotUrgentTag: " .. arg)
1183 -- wmiir xwrite "/lbar/$@" "$@"
1188 --[[
1189 =pod
1191 =item add_widget_event_handler (wname, ev, fn)
1193 Add an event handler callback for the I<ev> event on the widget named I<wname>
1195 =cut
1196 --]]
1198 function add_widget_event_handler (wname, ev, fn)
1199 if type(wname) ~= "string" or type(ev) ~= "string" or type(fn) ~= "function" then
1200 error ("expecting string for widget name, string for event name and a function callback")
1203 -- Make sure the widget event handler is present
1204 if not ev_handlers[ev] then
1205 ev_handlers[ev] = _handle_widget_event
1208 if not widget_ev_handlers[wname] then
1209 widget_ev_handlers[wname] = { }
1212 if widget_ev_handlers[wname][ev] then
1213 -- TODO: we may wish to allow multiple handlers for one event
1214 error ("event handler already exists on widget '" .. wname .. "' for '" .. ev .. "'")
1217 widget_ev_handlers[wname][ev] = fn
1220 --[[
1221 =pod
1223 =item remove_widget_event_handler (wname, ev)
1225 Remove an event handler callback function for the I<ev> on the widget named I<wname>.
1227 =cut
1228 --]]
1229 function remove_event_handler (wname, ev)
1231 if not widget_ev_handlers[wname] then
1232 return
1235 widget_ev_handlers[wname][ev] = nil
1238 --[[
1239 =pod
1241 =item add_event_handler (ev, fn)
1243 Add an event handler callback function, I<fn>, for the given event I<ev>.
1245 =cut
1246 --]]
1247 -- TODO: Need to allow registering widgets for RightBar* events. Should probably be done with its own event table, though
1248 function add_event_handler (ev, fn)
1249 if type(ev) ~= "string" or type(fn) ~= "function" then
1250 error ("expecting a string and a function")
1253 if ev_handlers[ev] then
1254 -- TODO: we may wish to allow multiple handlers for one event
1255 error ("event handler already exists for '" .. ev .. "'")
1259 ev_handlers[ev] = fn
1262 --[[
1263 =pod
1265 =item remove_event_handler (ev)
1267 Remove an event handler callback function for the given event I<ev>.
1269 =cut
1270 --]]
1271 function remove_event_handler (ev)
1273 ev_handlers[ev] = nil
1277 -- ========================================================================
1278 -- MAIN INTERFACE FUNCTIONS
1279 -- ========================================================================
1281 local config = {
1282 xterm = 'x-terminal-emulator',
1283 xlock = "xscreensaver-command --lock",
1284 debug = false,
1287 -- ------------------------------------------------------------------------
1288 -- write configuration to /ctl wmii file
1289 -- wmii.set_ctl({ "var" = "val", ...})
1290 -- wmii.set_ctl("var, "val")
1291 function set_ctl (first,second)
1292 if type(first) == "table" and second == nil then
1293 local x, y
1294 for x, y in pairs(first) do
1295 write ("/ctl", x .. " " .. y)
1298 elseif type(first) == "string" and type(second) == "string" then
1299 write ("/ctl", first .. " " .. second)
1301 else
1302 error ("expecting a table or two string arguments")
1306 -- ------------------------------------------------------------------------
1307 -- read a value from /ctl wmii file
1308 -- table = wmii.get_ctl()
1309 -- value = wmii.get_ctl("variable"
1310 function get_ctl (name)
1311 local s
1312 local t = {}
1313 for s in iread("/ctl") do
1314 local var,val = s:match("(%w+)%s+(.+)")
1315 if var == name then
1316 return val
1318 t[var] = val
1320 if not name then
1321 return t
1323 return nil
1326 -- ------------------------------------------------------------------------
1327 -- set an internal wmiirc.lua variable
1328 -- wmii.set_conf({ "var" = "val", ...})
1329 -- wmii.set_conf("var, "val")
1330 function set_conf (first,second)
1331 if type(first) == "table" and second == nil then
1332 local x, y
1333 for x, y in pairs(first) do
1334 config[x] = y
1337 elseif type(first) == "string"
1338 and (type(second) == "string"
1339 or type(second) == "number") then
1340 config[first] = second
1342 else
1343 error ("expecting a table, or string and string/number as arguments")
1347 -- ------------------------------------------------------------------------
1348 -- read an internal wmiirc.lua variable
1349 function get_conf (name)
1350 if name then
1351 return config[name]
1353 return config
1356 -- ========================================================================
1357 -- THE EVENT LOOP
1358 -- ========================================================================
1360 -- the event loop instance
1361 local el = eventloop.new()
1363 -- add the core event handler for events
1364 el:add_exec (wmiir .. " read /event",
1365 function (line)
1366 local line = line or "nil"
1368 -- try to split off the argument(s)
1369 local ev,arg = string.match(line, "(%S+)%s+(.+)")
1370 if not ev then
1371 ev = line
1374 -- now locate the handler function and call it
1375 local fn = ev_handlers[ev] or ev_handlers["*"]
1376 if fn then
1377 local r, err = pcall (fn, ev, arg)
1378 if not r then
1379 log ("WARNING: " .. tostring(err))
1382 end)
1384 -- ------------------------------------------------------------------------
1385 -- run the event loop and process events, this function does not exit
1386 function run_event_loop ()
1387 -- stop any other instance of wmiirc
1388 wmixp:write ("/event", "Start wmiirc " .. tostring(myid))
1390 log("wmii: updating lbar")
1392 update_displayed_tags ()
1394 log("wmii: updating rbar")
1396 update_displayed_widgets ()
1398 log("wmii: updating active keys")
1400 update_active_keys ()
1402 log("wmii: starting event loop")
1403 while true do
1404 local sleep_for = process_timers()
1405 el:run_loop(sleep_for)
1409 -- ========================================================================
1410 -- PLUGINS API
1411 -- ========================================================================
1413 api_version = 0.1 -- the API version we export
1415 plugins = {} -- all plugins that were loaded
1417 -- ------------------------------------------------------------------------
1418 -- plugin loader which also verifies the version of the api the plugin needs
1420 -- here is what it does
1421 -- - does a manual locate on the file using package.path
1422 -- - reads in the file w/o using the lua interpreter
1423 -- - locates api_version=X.Y string
1424 -- - makes sure that api_version requested can be satisfied
1425 -- - if the plugins is available it will set variables passed in
1426 -- - it then loads the plugin
1428 -- TODO: currently the api_version must be in an X.Y format, but we may want
1429 -- to expend this so plugins can say they want '0.1 | 1.3 | 2.0' etc
1431 function load_plugin(name, vars)
1432 local backup_path = package.path or "./?.lua"
1434 log ("loading " .. name)
1436 -- this is the version we want to find
1437 local api_major, api_minor = tostring(api_version):match("(%d+)%.0*(%d+)")
1438 if (not api_major) or (not api_minor) then
1439 log ("WARNING: could not parse api_version in core/wmii.lua")
1440 return nil
1443 -- first find the plugin file
1444 local s, path_match, full_name, file
1445 for s in string.gmatch(plugin_path, "[^;]+") do
1446 -- try to locate the files locally
1447 local fn = s:gsub("%?", name)
1448 file = io.open(fn, "r")
1449 if file then
1450 path_match = s
1451 full_name = fn
1452 break
1456 -- read it in
1457 local txt
1458 if file then
1459 txt = file:read("*all")
1460 file:close()
1463 if not txt then
1464 log ("WARNING: could not load plugin '" .. name .. "'")
1465 return nil
1468 -- find the api_version line
1469 local line, plugin_version
1470 for line in string.gmatch(txt, "%s*api_version%s*=%s*%d+%.%d+%s*") do
1471 plugin_version = line:match("api_version%s*=%s*(%d+%.%d+)%s*")
1472 if plugin_version then
1473 break
1477 if not plugin_version then
1478 log ("WARNING: could not find api_version string in plugin '" .. name .. "'")
1479 return nil
1482 -- decompose the version string
1483 local plugin_major, plugin_minor = plugin_version:match("(%d+)%.0*(%d+)")
1484 if (not plugin_major) or (not plugin_minor) then
1485 log ("WARNING: could not parse api_version for '" .. name .. "' plugin")
1486 return nil
1489 -- make a version test
1490 if plugin_major ~= api_major then
1491 log ("WARNING: " .. name .. " plugin major version missmatch, is " .. plugin_version
1492 .. " (api " .. tonumber(api_version) .. ")")
1493 return nil
1496 if plugin_minor > api_minor then
1497 log ("WARNING: '" .. name .. "' plugin minor version missmatch, is " .. plugin_version
1498 .. " (api " .. tonumber(api_version) .. ")")
1499 return nil
1502 -- the configuration parameters before loading
1503 if type(vars) == "table" then
1504 local var, val
1505 for var,val in pairs(vars) do
1506 local success = pcall (set_conf, name .. "." .. var, val)
1507 if not success then
1508 log ("WARNING: bad variable {" .. tostring(var) .. ", " .. tostring(val) .. "} "
1509 .. "given; loading '" .. name .. "' plugin failed.")
1510 return nil
1515 -- actually load the module, but use only the path where we though it should be
1516 package.path = path_match
1517 local success,what = pcall (require, name)
1518 package.path = backup_path
1519 if not success then
1520 log ("WARNING: failed to load '" .. name .. "' plugin")
1521 log (" - path: " .. tostring(path_match))
1522 log (" - file: " .. tostring(full_name))
1523 log (" - plugin's api_version: " .. tostring(plugin_version))
1524 log (" - reason: " .. tostring(what))
1525 return nil
1528 -- success
1529 log ("OK, plugin " .. name .. " loaded, requested api v" .. plugin_version)
1530 plugins[name] = what
1531 return what
1534 -- ------------------------------------------------------------------------
1535 -- widget template
1536 widget = {}
1537 widgets = {}
1539 -- ------------------------------------------------------------------------
1540 -- create a widget object and add it to the wmii /rbar
1542 -- examples:
1543 -- widget = wmii.widget:new ("999_clock")
1544 -- widget = wmii.widget:new ("999_clock", clock_event_handler)
1545 function widget:new (name, fn)
1546 local o = {}
1548 if type(name) == "string" then
1549 o.name = name
1550 if type(fn) == "function" then
1551 o.fn = fn
1553 else
1554 error ("expected name followed by an optional function as arguments")
1557 setmetatable (o,self)
1558 self.__index = self
1559 self.__gc = function (o) o:hide() end
1561 widgets[name] = o
1563 o:show()
1564 return o
1567 -- ------------------------------------------------------------------------
1568 -- stop and destroy the timer
1569 function widget:delete ()
1570 widgets[self.name] = nil
1571 self:hide()
1574 -- ------------------------------------------------------------------------
1575 -- displays or updates the widget text
1577 -- examples:
1578 -- w:show("foo")
1579 -- w:show("foo", "#888888 #222222 #333333")
1580 -- w:show("foo", cell_fg .. " " .. cell_bg .. " " .. border)
1582 function widget:show (txt, colors)
1583 local colors = colors or get_ctl("normcolors") or ""
1584 local txt = txt or self.txt or ""
1585 local towrite = txt
1586 if colors then
1587 towrite = colors .. " " .. towrite
1589 if not self.txt then
1590 create ("/rbar/" .. self.name, towrite)
1591 else
1592 write ("/rbar/" .. self.name, towrite)
1594 self.txt = txt
1597 -- ------------------------------------------------------------------------
1598 -- hides a widget and removes it from the bar
1599 function widget:hide ()
1600 if self.txt then
1601 remove ("/lbar/" .. self.name)
1602 self.txt = nil
1606 --[[
1607 =pod
1609 =item widget:add_event_handler (ev, fn)
1611 Add an event handler callback for this widget, using I<fn> for event I<ev>
1613 =cut
1614 --]]
1616 function widget:add_event_handler (ev, fn)
1617 add_widget_event_handler( self.name, ev, fn)
1621 -- ------------------------------------------------------------------------
1622 -- remove all /rbar entries that we don't have widget objects for
1623 function update_displayed_widgets ()
1624 -- colours for /rbar
1625 local nc = get_ctl("normcolors") or ""
1627 -- build up a table of existing tags in the /lbar
1628 local old = {}
1629 local s
1630 for s in wmixp:idir ("/rbar") do
1631 old[s.name] = 1
1634 -- for all actual widgets in use we want to remove them from the old list
1635 local i,v
1636 for i,v in pairs(widgets) do
1637 old[v.name] = nil
1640 -- anything left in the old table should be removed now
1641 for i,v in pairs(old) do
1642 if v then
1643 remove("/rbar/"..i)
1648 -- ------------------------------------------------------------------------
1649 -- create a new program and for each line it generates call the callback function
1650 -- returns fd which can be passed to kill_exec()
1651 function add_exec (command, callback)
1652 return el:add_exec (command, callback)
1655 -- ------------------------------------------------------------------------
1656 -- terminates a program spawned off by add_exec()
1657 function kill_exec (fd)
1658 return el:kill_exec (fd)
1661 -- ------------------------------------------------------------------------
1662 -- timer template
1663 timer = {}
1664 local timers = {}
1666 -- ------------------------------------------------------------------------
1667 -- create a timer object and add it to the event loop
1669 -- examples:
1670 -- timer:new (my_timer_fn)
1671 -- timer:new (my_timer_fn, 15)
1672 function timer:new (fn, seconds)
1673 local o = {}
1675 if type(fn) == "function" then
1676 o.fn = fn
1677 else
1678 error ("expected function followed by an optional number as arguments")
1681 setmetatable (o,self)
1682 self.__index = self
1683 self.__gc = function (o) o:stop() end
1685 -- add the timer
1686 timers[#timers+1] = o
1688 if seconds then
1689 o:resched(seconds)
1691 return o
1694 -- ------------------------------------------------------------------------
1695 -- stop and destroy the timer
1696 function timer:delete ()
1697 self:stop()
1698 local i,t
1699 for i,t in pairs(timers) do
1700 if t == self then
1701 table.remove (timers,i)
1702 return
1707 -- ------------------------------------------------------------------------
1708 -- run the timer given new interval
1709 function timer:resched (seconds)
1710 local seconds = seconds or self.interval
1711 if not (type(seconds) == "number") then
1712 error ("timer:resched expected number as argument")
1715 local now = tonumber(os.date("%s"))
1717 self.interval = seconds
1718 self.next_time = now + seconds
1720 -- resort the timer list
1721 table.sort (timers, timer.is_less_then)
1724 -- helper for sorting timers
1725 function timer:is_less_then(another)
1726 if not self.next_time then
1727 return false -- another is smaller, nil means infinity
1729 elseif not another.next_time then
1730 return true -- self is smaller, nil means infinity
1732 elseif self.next_time < another.next_time then
1733 return true -- self is smaller than another
1736 return false -- another is smaller then self
1739 -- ------------------------------------------------------------------------
1740 -- stop the timer
1741 function timer:stop ()
1742 self.next_time = nil
1744 -- resort the timer list
1745 table.sort (timers, timer.is_less_then)
1748 -- ------------------------------------------------------------------------
1749 -- figure out how long before the next event
1750 function time_before_next_timer_event()
1751 local tmr = timers[1]
1752 if tmr and tmr.next_time then
1753 local now = tonumber(os.date("%s"))
1754 local seconds = tmr.next_time - now
1755 if seconds > 0 then
1756 return seconds
1759 return 0 -- sleep for ever
1762 -- ------------------------------------------------------------------------
1763 -- handle outstanding events
1764 function process_timers ()
1765 local now = tonumber(os.date("%s"))
1766 local torun = {}
1767 local i,tmr
1769 for i,tmr in pairs (timers) do
1770 if not tmr then
1771 -- prune out removed timers
1772 table.remove(timers,i)
1773 break
1775 elseif not tmr.next_time then
1776 -- break out once we find a timer that is stopped
1777 break
1779 elseif tmr.next_time > now then
1780 -- break out once we get to the future
1781 break
1784 -- this one is good to go
1785 torun[#torun+1] = tmr
1788 for i,tmr in pairs (torun) do
1789 tmr:stop()
1790 local status,new_interval = pcall (tmr.fn, tmr)
1791 if status then
1792 new_interval = new_interval or self.interval
1793 if new_interval and (new_interval ~= -1) then
1794 tmr:resched(new_interval)
1796 else
1797 log ("ERROR: " .. tostring(new_interval))
1801 local sleep_for = time_before_next_timer_event()
1802 return sleep_for
1805 -- ------------------------------------------------------------------------
1806 -- cleanup everything in preparation for exit() or exec()
1807 function cleanup ()
1809 local i,v,tmr,p
1811 log ("wmii: stopping timer events")
1813 for i,tmr in pairs (timers) do
1814 pcall (tmr.delete, tmr)
1816 timers = {}
1818 log ("wmii: terminating eventloop")
1820 pcall(el.kill_all,el)
1822 log ("wmii: disposing of widgets")
1824 -- dispose of all widgets
1825 for i,v in pairs(widgets) do
1826 pcall(v.delete,v)
1828 timers = {}
1830 -- FIXME: it doesn't seem to do what I want
1831 --[[
1832 log ("wmii: releasing plugins")
1834 for i,p in pairs(plugins) do
1835 if p.cleanup then
1836 pcall (p.cleanup, p)
1839 plugins = {}
1840 --]]
1842 log ("wmii: dormant")
1845 -- ========================================================================
1846 -- CLIENT HANDLING
1847 -- ========================================================================
1849 --[[
1850 -- Notes on client tracking
1852 -- When a client is created wmii sends us a CreateClient message, and
1853 -- we in turn create a 'client' object and store it in the 'clients'
1854 -- table indexed by the client's ID.
1856 -- Each client object stores the following:
1857 -- .xid - the X client ID
1858 -- .pid - the process ID
1859 -- .prog - program object representing the process
1861 -- The client and program objects track the following modes for each program:
1863 -- raw mode:
1864 -- - for each client window
1865 -- - Mod4-space toggles the state between normal and raw
1866 -- - Mod1-f raw also toggles the state
1867 -- - in raw mode all input goes to the client, except for Mod4-space
1868 -- - a focused client with raw mode enabled is put into raw mode
1870 -- suspend mode:
1871 -- - for each program
1872 -- - Mod1-f suspend toggles the state for current client's program
1873 -- - a focused client, whose program was previous suspended is resumed
1874 -- - an unfocused client, with suspend enabled, will be suspended
1875 -- - suspend/resume is done by sending the STOP/CONT signals to the PID
1876 --]]
1878 function xid_to_pid (xid)
1879 local cmd = "xprop -id " .. tostring(xid) .. " _NET_WM_PID"
1880 local file = io.popen (cmd)
1881 local out = file:read("*a")
1882 file:close()
1883 local pid = out:match("^_NET_WM_PID.*%s+=%s+(%d+)%s+$")
1884 return tonumber(pid)
1887 local focused_xid = nil
1888 local clients = {} -- table of client objects indexed by xid
1889 local programs = {} -- table of program objects indexed by pid
1890 local mode_widget = widget:new ("999_client_mode")
1892 -- make programs table have weak values
1893 -- programs go away as soon as no clients point to it
1894 local programs_mt = {}
1895 setmetatable(programs, programs_mt)
1896 programs_mt.__mode = 'v'
1898 -- program class
1899 program = {}
1900 function program:new (pid)
1901 -- make an object
1902 local o = {}
1903 setmetatable (o,self)
1904 self.__index = self
1905 self.__gc = function (old) old:cont() end
1906 -- initialize the new object
1907 o.pid = pid
1908 -- suspend mode
1909 o.suspend = {}
1910 o.suspend.toggle = function (prog)
1911 prog.suspend.enabled = not prog.suspend.enabled
1913 o.suspend.enabled = false -- if true, defocusing suspends (SIGSTOP)
1914 o.suspend.active = true -- if true, focusing resumes (SIGCONT)
1915 return o
1918 function program:stop ()
1919 if not self.suspend.active then
1920 local cmd = "kill -STOP " .. tostring(self.pid)
1921 log (" executing: " .. cmd)
1922 os.execute (cmd)
1923 self.suspend.active = true
1927 function program:cont ()
1928 if self.suspend.active then
1929 local cmd = "kill -CONT " .. tostring(self.pid)
1930 log (" executing: " .. cmd)
1931 os.execute (cmd)
1932 self.suspend.active = false
1936 function get_program (pid)
1937 local prog = programs[pid]
1938 if not prog then
1939 prog = program:new (pid)
1940 programs[pid] = prog
1942 return prog
1945 -- client class
1946 client = {}
1947 function client:new (xid)
1948 -- make an object
1949 local o = {}
1950 setmetatable (o,self)
1951 self.__index = function (t,k)
1952 if k == 'suspend' then -- suspend mode is tracked per program
1953 return t.prog.suspend
1955 return self[k]
1957 self.__gc = function (old) old.prog=nil end
1958 -- initialize the new object
1959 o.xid = xid
1960 o.pid = xid_to_pid(xid)
1961 o.prog = get_program (o.pid)
1962 -- raw mode
1963 o.raw = {}
1964 o.raw.toggle = function (cli)
1965 cli.raw.enabled = not cli.raw.enabled
1966 cli:set_raw_mode()
1968 o.raw.enabled = false -- if true, raw mode enabled when client is focused
1969 return o
1972 function client:stop ()
1973 if self.suspend.enabled then
1974 self.prog:stop()
1978 function client:cont ()
1979 self.prog:cont()
1982 function client:set_raw_mode()
1983 if not self or not self.raw.enabled then -- normal mode
1984 update_active_keys ()
1985 else -- raw mode
1986 write ("/keys", "Mod4-space")
1990 function client:toggle(what)
1991 if what and self[what] then
1992 local ctl = self[what]
1994 ctl.toggle (self)
1996 log ("xid=" .. tostring (xid)
1997 .. " pid=" .. tostring (self.pid) .. " (" .. tostring (self.prog.pid) .. ")"
1998 .. " what=" .. tostring (what)
1999 .. " enabled=" .. tostring(ctl["enabled"]))
2001 mode_widget:show (self:flags_string())
2004 function client:flags_string()
2005 local ret = ''
2006 if self.suspend.enabled then ret = ret .. "s" else ret = ret .. "-" end
2007 if self.raw.enabled then ret = ret .. "r" else ret = ret .. "-" end
2008 return ret
2011 function get_client (xid)
2012 local xid = xid or wmixp:read("/client/sel/ctl")
2013 local cli = clients[xid]
2014 if not cli then
2015 cli = client:new (xid)
2016 clients[xid] = cli
2018 return cli
2021 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
2022 function client_created (xid)
2023 log ("-client_created " .. tostring(xid))
2024 return get_client(xid)
2027 function client_destoryed (xid)
2028 log ("-client_destoryed " .. tostring(xid))
2029 if clients[xid] then
2030 local cli = clients[xid]
2031 clients[xid] = nil
2032 log (" del pid: " .. tostring(cli.pid))
2033 cli:cont()
2037 function client_focused (xid)
2038 log ("-client_focused " .. tostring(xid))
2039 -- do nothing if the same xid
2040 if focused_xid == xid then
2041 return clients[xid]
2044 local old = clients[focused_xid]
2045 local new = get_client(xid)
2047 -- handle raw mode switch
2048 if not old or ( old and new and old.raw.enabled ~= new.raw.enabled ) then
2049 new:set_raw_mode()
2052 -- do nothing if the same pid
2053 if old and new and old.pid == new.pid then
2054 mode_widget:show (new:flags_string())
2055 return clients[xid]
2058 if old then
2059 --[[
2060 log (" old pid: " .. tostring(old.pid)
2061 .. " xid: " .. tostring(old.xid)
2062 .. " flags: " .. old:flags_string())
2063 ]]--
2064 old:stop()
2067 if new then
2068 --[[
2069 log (" new pid: " .. tostring(new.pid)
2070 .. " xid: " .. tostring(new.xid)
2071 .. " flags: " .. new:flags_string())
2072 ]]--
2073 new:cont()
2076 mode_widget:show (new:flags_string())
2077 focused_xid = xid
2078 return new
2082 -- ========================================================================
2083 -- DOCUMENTATION
2084 -- ========================================================================
2086 --[[
2087 =pod
2089 =back
2091 =head1 ENVIRONMENT
2093 =over 4
2095 =item WMII_ADDRESS
2097 Used to determine location of wmii's listen socket.
2099 =back
2101 =head1 SEE ALSO
2103 L<wmii(1)>, L<lua(1)>
2105 =head1 AUTHOR
2107 Bart Trojanowski B<< <bart@jukie.net> >>
2109 =head1 COPYRIGHT AND LICENSE
2111 Copyright (c) 2007, Bart Trojanowski <bart@jukie.net>
2113 This is free software. You may redistribute copies of it under the terms of
2114 the GNU General Public License L<http://www.gnu.org/licenses/gpl.html>. There
2115 is NO WARRANTY, to the extent permitted by law.
2117 =cut
2118 --]]