2 -- Copyright (c) 2007, Bart Trojanowski <bart@jukie.net>
4 -- WMII event loop, in lua
6 -- http://www.jukie.net/~bart/blog/tag/wmiirc-lua
7 -- git://www.jukie.net/wmiirc-lua.git/
10 -- ========================================================================
12 -- ========================================================================
18 wmii.lua - WMII event-loop methods in lua
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
32 -- Configure wmii.lua parameters
34 xterm = 'x-terminal-emulator'
37 -- Now start the event loop
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
54 -- ========================================================================
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;" ..
64 package
.cpath
= wmiidir
.. "/core/?.so;" ..
65 wmiidir
.. "/plugins/?.so;" ..
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")
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")
97 myid
= posix
.getprocessid("pid")
99 local now
= tonumber(os
.date("%s"))
101 myid
= math
.random(10000)
104 -- ========================================================================
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 -- ========================================================================
147 -- ========================================================================
154 Log the message provided in C<str>
156 Currently just writes to io.stderr
161 if get_conf("debug") then
162 io
.stderr
:write (str
.. "\n")
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
177 function find_wmiirc()
179 for fn
in string.gmatch(wmiirc_path
, "[^;]+") do
180 -- try to locate the files locally
181 local file
= io
.open(fn
, "r")
183 local txt
= file
:read("*line")
185 if type(txt
) == 'string' and txt
:match("lua") then
194 -- ========================================================================
195 -- MAIN ACCESS FUNCTIONS
196 -- ========================================================================
201 =item ls ( dir, fmt )
203 List the wmii filesystem directory provided in C<dir>, in the format specified
206 Returns an iterator of TODO
210 function ls (dir
, fmt
)
211 local verbose
= fmt
and fmt
:match("l")
213 local s
= wmixp
:stat(dir
)
215 return function () return nil end
217 if s
.modestr
:match("^[^d]") then
219 return stat2str(verbose
, s
)
223 local itr
= wmixp
:idir (dir
)
234 return stat2str(verbose
, s
)
240 local function stat2str(verbose
, stat
)
242 return string.format("%s %s %s %5d %s %s", stat
.modestr
, stat
.uid
, stat
.gid
, stat
.length
, stat
.timestr
, stat
.name
)
244 if stat
.modestr
:match("^d") then
245 return stat
.name
.. "/"
252 -- ------------------------------------------------------------------------
253 -- read all contents of a wmii virtual file
255 return wmixp
:read (file
)
258 -- ------------------------------------------------------------------------
259 -- return an iterator which walks all the lines in the file
262 -- for event in wmii.iread("/ctl")
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
)
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")
297 cmdt
[#cmdt
+1] = "-fn"
300 local normcolors
= get_ctl("normcolors")
302 local nf
, nb
= normcolors
:match("(#%x+)%s+(#%x+)%s#%x+")
304 cmdt
[#cmdt
+1] = "-nf"
305 cmdt
[#cmdt
+1] = "'" .. nf
.. "'"
308 cmdt
[#cmdt
+1] = "-nb"
309 cmdt
[#cmdt
+1] = "'" .. nb
.. "'"
312 local focuscolors
= get_ctl("focuscolors")
314 local sf
, sb
= focuscolors
:match("(#%x+)%s+(#%x+)%s#%x+")
316 cmdt
[#cmdt
+1] = "-sf"
317 cmdt
[#cmdt
+1] = "'" .. sf
.. "'"
320 cmdt
[#cmdt
+1] = "-sb"
321 cmdt
[#cmdt
+1] = "'" .. sb
.. "'"
326 cmdt
[#cmdt
+1] = "'" .. prompt
.. "'"
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+")
341 for i
,v
in pairs(tbl
) do
342 if type(i
) == 'number' and type(v
) == 'string' then
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
," ")
361 fh
= io
.open (outfile
, "r")
364 local sel
= fh
:read("*l")
370 -- ------------------------------------------------------------------------
371 -- displays the a tag selection menu, returns selected tag
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
389 for n
in prog_hist
:walk_reverse_unique() do
390 hstt
[#hstt
+1] = "echo '" .. n
.. "' ; "
393 local cmd
= "(" .. table.concat(hstt
)
395 .. table.concat(dmenu
," ")
398 local fh
= io
.open (outfile
, "rb")
401 local prog
= fh
:read("*l")
407 -- ------------------------------------------------------------------------
408 -- displays the a program menu, returns selected program
412 for s
in wmixp
:idir ("/tag") do
413 if s
.name
and not (s
.name
== "sel") then
421 -- ------------------------------------------------------------------------
422 -- displays the a program menu, returns selected program
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
439 if not (type(sel
) == "string") then
440 error ("string argument expected")
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()
454 -- nothing to do if we have less then 2 tags
458 local num
= tonumber (sel
)
460 error ("number argument expected")
463 local name
= all
[sel
]
464 if not name
or name
== cur
then
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()
479 -- nothing to do if we have less then 2 tags
484 if (jump
< - #all
) or (jump
> #all
) then
485 error ("view selector is out of range")
488 -- find the one that's selected index
491 for i
,v
in pairs (all
) do
492 if v
== cur
then curi
= i
end
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
]
513 -- ========================================================================
515 -- ========================================================================
517 local action_handlers
= {
518 man
= function (act
, args
)
519 local xterm
= get_conf("xterm") or "xterm"
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
)
530 write ("/ctl", "quit")
533 exec
= function (act
, args
)
534 local what
= args
or "wmii"
535 log (" asking wmii to exec " .. tostring(what
))
537 write ("/ctl", "exec " .. what
)
540 xlock
= function (act
)
541 local cmd
= get_conf("xlock") or "xscreensaver-command --lock"
547 local wmiirc
= find_wmiirc()
549 log (" executing: lua " .. wmiirc
)
551 posix
.exec ("lua", wmiirc
)
554 log("sorry cannot restart; you don't have lua's posix library.")
560 -- TODO: consider storing list of executables around, and
561 -- this will then reinitialize that list
562 log (" TODO: rehash")
566 -- TODO: this should eventually update something on the /rbar
567 log (" TODO: status")
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>.
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
597 =item remove_action_handler (action)
599 Remove an action handler callback function for the given action string I<action>.
603 function remove_action_handler (action
)
605 action_handlers
[action
] = nil
608 -- ========================================================================
610 -- ========================================================================
612 function ke_view_starting_with_letter (letter
)
615 -- find the view name in history in reverse order
616 for i
=#view_hist
,1,-1 do
618 if letter
== v
:sub(1,1) then
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
636 function ke_handle_action()
641 for n
in action_hist
:walk_reverse() do
643 actions
[#actions
+1] = n
649 for n
,v
in pairs(action_handlers
) do
651 actions
[#actions
+1] = n
656 local text
= menu(actions
, "action:")
658 log ("Action: " .. text
)
661 local si
= text
:find("%s")
663 act
,args
= string.match(text
.. " ", "(%w+)%s(.+)")
666 local fn
= action_handlers
[act
]
668 action_hist
:add (act
)
669 local r
, err
= pcall (fn
, act
, args
)
671 log ("WARNING: " .. tostring(err
))
679 local key_handlers
= {
680 ["*"] = function (key
)
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
.. " &")
690 ["Mod1-Shift-Return"] = function (key
)
691 local tag = tag_menu()
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
.. " &")
699 ["Mod1-a"] = function (key
)
702 ["Mod1-p"] = function (key
)
703 local prog
= prog_menu()
705 prog_hist
:add(prog
:match("(%w+)"))
706 log (" executing: " .. prog
)
707 os
.execute (prog
.. " &")
710 ["Mod1-Shift-p"] = function (key
)
711 local tag = tag_menu()
713 local prog
= prog_menu()
715 log (" executing: " .. prog
.. " on: " .. tag)
716 next_client_goes_to_tag
= tag
717 os
.execute (prog
.. " &")
721 ["Mod1-Shift-c"] = function (key
)
722 write ("/client/sel/ctl", "kill")
725 -- HJKL active selection
726 ["Mod1-h"] = function (key
)
727 write ("/tag/sel/ctl", "select left")
729 ["Mod1-l"] = function (key
)
730 write ("/tag/sel/ctl", "select right")
732 ["Mod1-j"] = function (key
)
733 write ("/tag/sel/ctl", "select down")
735 ["Mod1-k"] = function (key
)
736 write ("/tag/sel/ctl", "select up")
740 ["Mod1-Shift-h"] = function (key
)
741 write ("/tag/sel/ctl", "send sel left")
743 ["Mod1-Shift-l"] = function (key
)
744 write ("/tag/sel/ctl", "send sel right")
746 ["Mod1-Shift-j"] = function (key
)
747 write ("/tag/sel/ctl", "send sel down")
749 ["Mod1-Shift-k"] = function (key
)
750 write ("/tag/sel/ctl", "send sel up")
754 ["Mod1-space"] = function (key
)
755 write ("/tag/sel/ctl", "select toggle")
757 ["Mod1-Shift-space"] = function (key
)
758 write ("/tag/sel/ctl", "send sel toggle")
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
770 ["Mod4-Shift-#"] = function (key
, num
)
771 write ("/client/sel/tags", tostring(num
))
773 ["Mod4-@"] = function (key
, letter
)
774 ke_view_starting_with_letter (letter
)
776 ["Mod4-Shift-@"] = function (key
, letter
)
777 local all
= get_tags()
779 for i
,v
in pairs(all
) do
780 if letter
== v
:sub(1,1) then
781 write ("/client/sel/tags", v
)
786 ["Mod1-comma"] = function (key
)
789 ["Mod1-period"] = function (key
)
792 ["Mod1-r"] = function (key
)
793 -- got to the last view
797 -- switching views and retagging
798 ["Mod1-t"] = function (key
)
800 local tag = tag_menu()
805 ["Mod1-Shift-t"] = function (key
)
806 -- move selected client to a tag
807 local tag = tag_menu()
809 write ("/client/sel/tags", tag)
812 ["Mod1-Shift-r"] = function (key
)
813 -- move selected client to a tag, and follow
814 local tag = tag_menu()
816 write ("/client/sel/tags", tag)
820 ["Mod1-Control-t"] = function (key
)
821 log (" TODO: Mod1-Control-t: " .. key
)
825 ["Mod1-d"] = function (key
)
826 write("/tag/sel/ctl", "colmode sel default")
828 ["Mod1-s"] = function (key
)
829 write("/tag/sel/ctl", "colmode sel stack")
831 ["Mod1-m"] = function (key
)
832 write("/tag/sel/ctl", "colmode sel max")
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:")
848 ["Mod4-space"] = function (key
)
849 local cli
= get_client ()
857 =item add_key_handler (key, fn)
859 Add a keypress handler callback function, I<fn>, for the given key sequence I<key>.
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
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.
888 function remove_key_handler (key
)
890 local fn
= key_handlers
[key
]
891 key_handlers
[key
] = nil
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>.
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 ()
919 for x
,y
in pairs(key_handlers
) do
921 local i
= x
:find("#$")
925 t
[#t
+ 1] = x
:sub(1,i
-1) .. 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
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 ()
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
956 for s
in wmixp
:idir ("/lbar") do
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()
965 for i
,v
in pairs(all
) do
971 create ("/lbar/" .. v
, color
.. " " .. v
)
973 write ("/lbar/" .. v
, color
.. " " .. v
)
977 -- anything left in the old table should be removed now
978 for i
,v
in pairs(old
) do
985 -- ========================================================================
987 -- ========================================================================
989 local widget_ev_handlers
= {
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
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
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
1023 log("Didn't find wname")
1027 local wtable
= widget_ev_handlers
[wname
]
1029 log("No widget cares about" .. wname
)
1033 local fn
= wtable
[ev
] or wtable
["*"]
1035 success
, err
= pcall( fn
, ev
, tonumber(number) )
1037 log("Callback had an error in _handle_widget_event: " .. tostring(err
) )
1041 log("no function found for " .. ev
)
1045 local ev_handlers
= {
1046 ["*"] = function (ev
, arg
)
1047 log ("ev: " .. tostring(ev
) .. " - " .. tostring(arg
))
1050 RightBarClick
= _handle_widget_event
,
1052 -- process timer events
1053 ProcessTimerEvents
= function (ev
, arg
)
1057 -- exit if another wmiirc started up
1058 Start
= function (ev
, arg
)
1060 if arg
== "wmiirc" then
1061 -- backwards compatibility with bash version
1062 log (" exiting; pid=" .. tostring(myid
))
1066 -- ignore if it came from us
1067 local pid
= string.match(arg
, "wmiirc (%d+)")
1069 local pid
= tonumber (pid
)
1070 if not (pid
== myid
) then
1071 log (" exiting; pid=" .. tostring(myid
))
1081 CreateTag
= function (ev
, arg
)
1082 local nc
= get_ctl("normcolors") or ""
1083 create ("/lbar/" .. arg
, nc
.. " " .. arg
)
1085 DestroyTag
= function (ev
, arg
)
1086 remove ("/lbar/" .. arg
)
1089 FocusTag
= function (ev
, arg
)
1090 local fc
= get_ctl("focuscolors") or ""
1091 create ("/lbar/" .. arg
, fc
.. " " .. arg
)
1092 write ("/lbar/" .. arg
, fc
.. " " .. arg
)
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)
1110 -- key event handling
1111 Key
= function (ev
, arg
)
1112 log ("Key: " .. arg
)
1114 -- can we find an exact match?
1115 local fn
= key_handlers
[arg
]
1117 local key
= arg
:gsub("-%d$", "-#")
1118 -- can we find a match with a # wild card for the number
1119 fn
= key_handlers
[key
]
1121 -- convert the trailing number to a number
1122 magic
= tonumber(arg
:match("-(%d)$"))
1126 local key
= arg
:gsub("-%a$", "-@")
1127 -- can we find a match with a @ wild card for a letter
1128 fn
= key_handlers
[key
]
1130 -- split off the trailing letter
1131 magic
= arg
:match("-(%a)$")
1135 -- everything else failed, try default match
1136 fn
= key_handlers
["*"]
1139 local r
, err
= pcall (fn
, arg
, magic
)
1141 log ("WARNING: " .. tostring(err
))
1146 -- mouse handling on the lbar
1147 LeftBarClick
= function (ev
, arg
)
1148 local button
,tag = string.match(arg
, "(%w+)%s+(%S+)")
1153 ClientFocus
= function (ev
, arg
)
1154 log ("ClientFocus: " .. arg
)
1155 client_focused (arg
)
1157 ColumnFocus
= function (ev
, arg
)
1158 log ("ColumnFocus: " .. arg
)
1162 CreateClient
= function (ev
, arg
)
1163 if next_client_goes_to_tag
then
1164 local tag = next_client_goes_to_tag
1166 next_client_goes_to_tag
= nil
1167 write ("/client/" .. cli
.. "/tags", tag)
1170 client_created (arg
)
1172 DestroyClient
= function (ev
, arg
)
1173 client_destoryed (arg
)
1177 UrgentTag
= function (ev
, arg
)
1178 log ("UrgentTag: " .. arg
)
1179 -- wmiir xwrite "/lbar/$@" "*$@"
1181 NotUrgentTag
= function (ev
, arg
)
1182 log ("NotUrgentTag: " .. arg
)
1183 -- wmiir xwrite "/lbar/$@" "$@"
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>
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
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>.
1229 function remove_event_handler (wname
, ev
)
1231 if not widget_ev_handlers
[wname
] then
1235 widget_ev_handlers
[wname
][ev
] = nil
1241 =item add_event_handler (ev, fn)
1243 Add an event handler callback function, I<fn>, for the given event I<ev>.
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
1265 =item remove_event_handler (ev)
1267 Remove an event handler callback function for the given event I<ev>.
1271 function remove_event_handler (ev
)
1273 ev_handlers
[ev
] = nil
1277 -- ========================================================================
1278 -- MAIN INTERFACE FUNCTIONS
1279 -- ========================================================================
1282 xterm
= 'x-terminal-emulator',
1283 xlock
= "xscreensaver-command --lock",
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
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
)
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
)
1313 for s
in iread("/ctl") do
1314 local var
,val
= s
:match("(%w+)%s+(.+)")
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
1333 for x
, y
in pairs(first
) do
1337 elseif type(first
) == "string"
1338 and (type(second
) == "string"
1339 or type(second
) == "number") then
1340 config
[first
] = second
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
)
1356 -- ========================================================================
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",
1366 local line
= line
or "nil"
1368 -- try to split off the argument(s)
1369 local ev
,arg
= string.match(line
, "(%S+)%s+(.+)")
1374 -- now locate the handler function and call it
1375 local fn
= ev_handlers
[ev
] or ev_handlers
["*"]
1377 local r
, err
= pcall (fn
, ev
, arg
)
1379 log ("WARNING: " .. tostring(err
))
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")
1404 local sleep_for
= process_timers()
1405 el
:run_loop(sleep_for
)
1409 -- ========================================================================
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")
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")
1459 txt
= file
:read("*all")
1464 log ("WARNING: could not load plugin '" .. name
.. "'")
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
1477 if not plugin_version
then
1478 log ("WARNING: could not find api_version string in plugin '" .. name
.. "'")
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")
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
) .. ")")
1496 if plugin_minor
> api_minor
then
1497 log ("WARNING: '" .. name
.. "' plugin minor version missmatch, is " .. plugin_version
1498 .. " (api " .. tonumber(api_version
) .. ")")
1502 -- the configuration parameters before loading
1503 if type(vars
) == "table" then
1505 for var
,val
in pairs(vars
) do
1506 local success
= pcall (set_conf
, name
.. "." .. var
, val
)
1508 log ("WARNING: bad variable {" .. tostring(var
) .. ", " .. tostring(val
) .. "} "
1509 .. "given; loading '" .. name
.. "' plugin failed.")
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
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
))
1529 log ("OK, plugin " .. name
.. " loaded, requested api v" .. plugin_version
)
1530 plugins
[name
] = what
1534 -- ------------------------------------------------------------------------
1539 -- ------------------------------------------------------------------------
1540 -- create a widget object and add it to the wmii /rbar
1543 -- widget = wmii.widget:new ("999_clock")
1544 -- widget = wmii.widget:new ("999_clock", clock_event_handler)
1545 function widget
:new (name
, fn
)
1548 if type(name
) == "string" then
1550 if type(fn
) == "function" then
1554 error ("expected name followed by an optional function as arguments")
1557 setmetatable (o
,self
)
1559 self
.__gc
= function (o
) o
:hide() end
1567 -- ------------------------------------------------------------------------
1568 -- stop and destroy the timer
1569 function widget
:delete ()
1570 widgets
[self
.name
] = nil
1574 -- ------------------------------------------------------------------------
1575 -- displays or updates the widget text
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 ""
1587 towrite
= colors
.. " " .. towrite
1589 if not self
.txt
then
1590 create ("/rbar/" .. self
.name
, towrite
)
1592 write ("/rbar/" .. self
.name
, towrite
)
1597 -- ------------------------------------------------------------------------
1598 -- hides a widget and removes it from the bar
1599 function widget
:hide ()
1601 remove ("/lbar/" .. self
.name
)
1609 =item widget:add_event_handler (ev, fn)
1611 Add an event handler callback for this widget, using I<fn> for event I<ev>
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
1630 for s
in wmixp
:idir ("/rbar") do
1634 -- for all actual widgets in use we want to remove them from the old list
1636 for i
,v
in pairs(widgets
) do
1640 -- anything left in the old table should be removed now
1641 for i
,v
in pairs(old
) do
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 -- ------------------------------------------------------------------------
1666 -- ------------------------------------------------------------------------
1667 -- create a timer object and add it to the event loop
1670 -- timer:new (my_timer_fn)
1671 -- timer:new (my_timer_fn, 15)
1672 function timer
:new (fn
, seconds
)
1675 if type(fn
) == "function" then
1678 error ("expected function followed by an optional number as arguments")
1681 setmetatable (o
,self
)
1683 self
.__gc
= function (o
) o
:stop() end
1686 timers
[#timers
+1] = o
1694 -- ------------------------------------------------------------------------
1695 -- stop and destroy the timer
1696 function timer
:delete ()
1699 for i
,t
in pairs(timers
) do
1701 table.remove (timers
,i
)
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 -- ------------------------------------------------------------------------
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
1759 return 0 -- sleep for ever
1762 -- ------------------------------------------------------------------------
1763 -- handle outstanding events
1764 function process_timers ()
1765 local now
= tonumber(os
.date("%s"))
1769 for i
,tmr
in pairs (timers
) do
1771 -- prune out removed timers
1772 table.remove(timers
,i
)
1775 elseif not tmr
.next_time
then
1776 -- break out once we find a timer that is stopped
1779 elseif tmr
.next_time
> now
then
1780 -- break out once we get to the future
1784 -- this one is good to go
1785 torun
[#torun
+1] = tmr
1788 for i
,tmr
in pairs (torun
) do
1790 local status
,new_interval
= pcall (tmr
.fn
, tmr
)
1792 new_interval
= new_interval
or self
.interval
1793 if new_interval
and (new_interval
~= -1) then
1794 tmr
:resched(new_interval
)
1797 log ("ERROR: " .. tostring(new_interval
))
1801 local sleep_for
= time_before_next_timer_event()
1805 -- ------------------------------------------------------------------------
1806 -- cleanup everything in preparation for exit() or exec()
1811 log ("wmii: stopping timer events")
1813 for i
,tmr
in pairs (timers
) do
1814 pcall (tmr
.delete
, tmr
)
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
1830 -- FIXME: it doesn't seem to do what I want
1832 log ("wmii: releasing plugins")
1834 for i,p in pairs(plugins) do
1836 pcall (p.cleanup, p)
1842 log ("wmii: dormant")
1845 -- ========================================================================
1847 -- ========================================================================
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:
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
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
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")
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'
1900 function program
:new (pid
)
1903 setmetatable (o
,self
)
1905 self
.__gc
= function (old
) old
:cont() end
1906 -- initialize the new object
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)
1918 function program
:stop ()
1919 if not self
.suspend
.active
then
1920 local cmd
= "kill -STOP " .. tostring(self
.pid
)
1921 log (" executing: " .. 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
)
1932 self
.suspend
.active
= false
1936 function get_program (pid
)
1937 local prog
= programs
[pid
]
1939 prog
= program
:new (pid
)
1940 programs
[pid
] = prog
1947 function client
:new (xid
)
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
1957 self
.__gc
= function (old
) old
.prog
=nil end
1958 -- initialize the new object
1960 o
.pid
= xid_to_pid(xid
)
1961 o
.prog
= get_program (o
.pid
)
1964 o
.raw
.toggle
= function (cli
)
1965 cli
.raw
.enabled
= not cli
.raw
.enabled
1968 o
.raw
.enabled
= false -- if true, raw mode enabled when client is focused
1972 function client
:stop ()
1973 if self
.suspend
.enabled
then
1978 function client
:cont ()
1982 function client
:set_raw_mode()
1983 if not self
or not self
.raw
.enabled
then -- normal mode
1984 update_active_keys ()
1986 write ("/keys", "Mod4-space")
1990 function client
:toggle(what
)
1991 if what
and self
[what
] then
1992 local ctl
= self
[what
]
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()
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
2011 function get_client (xid
)
2012 local xid
= xid
or wmixp
:read("/client/sel/ctl")
2013 local cli
= clients
[xid
]
2015 cli
= client
:new (xid
)
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
]
2032 log (" del pid: " .. tostring(cli
.pid
))
2037 function client_focused (xid
)
2038 log ("-client_focused " .. tostring(xid
))
2039 -- do nothing if the same xid
2040 if focused_xid
== xid
then
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
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())
2060 log (" old pid: " .. tostring(old.pid)
2061 .. " xid: " .. tostring(old.xid)
2062 .. " flags: " .. old:flags_string())
2069 log (" new pid: " .. tostring(new.pid)
2070 .. " xid: " .. tostring(new.xid)
2071 .. " flags: " .. new:flags_string())
2076 mode_widget
:show (new
:flags_string())
2082 -- ========================================================================
2084 -- ========================================================================
2097 Used to determine location of wmii's listen socket.
2103 L<wmii(1)>, L<lua(1)>
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.