Debian Codegraph @

flaw/helper.lua

raw symbols SCIP
1 -- flaw, a Lua OO management framework for Awesome WM widgets.
2 -- Copyright (C) 2009,2010,2011 David Soulayrol <david.soulayrol AT gmail DOT net>
3
4 -- This program is free software: you can redistribute it and/or modify
5 -- it under the terms of the GNU General Public License as published by
6 -- the Free Software Foundation, either version 3 of the License, or
7 -- (at your option) any later version.
8
9 -- This program is distributed in the hope that it will be useful,
10 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
11 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 -- GNU General Public License for more details.
13
14 -- You should have received a copy of the GNU General Public License
15 -- along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17
18 -- Grab environment.
19 local io = io
20 local os = os
21 local math = math
22 local pairs = pairs
23 local string = string
24 local tostring = tostring
25
26 local table = require('table')
27
28 local naughty = require('naughty')
29 local beautiful = require('beautiful')
30
31 --- Utilities.
32 --
33 -- <p>This module mainly contains utilities borrowed and improved from
34 -- wicked and other scripts found on the <b>awesome</b> wiki. Many
35 -- thanks to all the wiki contributors.</p>
36 --
37 --
38 -- @author David Soulayrol &lt;david.soulayrol AT gmail DOT com&gt;
39 -- @copyright 2009,2010,2011 David Soulayrol
40
41 module('flaw.helper')
42
43 local unities = { 'b', 'Kb', 'Mb', 'Gb', 'Tb' }
44
45 --- File related tools.
46 --
47 -- @class table
48 -- @name file
49 file = {}
50
51 --- Append the given string to a temporary log file.
52 --
53 -- @param line the line to write down.
54 function file.log(line)
55 if line ~= nil then
56 local log = io.open('/tmp/awesome_rc.log', 'a')
57 log:write(os.date('%c\t') .. tostring(line) .. '\n')
58 log:close()
59 end
60 end
61
62 --- Load a file with lines formatted as "name: value".
63 --
64 -- <p>For each line "k:v" read in the file f, the given table is
65 -- completed with v for the key "f_k" (everything in lower
66 -- case). Spaces in k are replaces with underscores.</p>
67 --
68 -- @param path the file path.
69 -- @param name the filename.
70 -- @param t the table which will hold the parsed values.
71 -- @return the number of lines parsed, or -1 if the file could not be opened.
72 function file.load_state_file(path, name, t)
73 local f = io.open(path .. '/' .. name)
74 local r = -1
75
76 if f ~= nil then
77 local prefix = name:lower() .. '_'
78 local line = nil
79 r = 0
80 repeat
81 line = f:read()
82 if line then
83 n, v = line:match('([%a%d ]+):%s+([%w%.- ]+)')
84 if n ~= nil and v ~= nil then
85 t[prefix .. n:gsub(' ', '_'):lower()] = v:lower()
86 r = r + 1
87 end
88 end
89 until line == nil
90 f:close()
91 end
92 return r
93 end
94
95 --- Text formatting related functions.
96 --
97 -- <p>This family of functions returns the given text formatted with
98 -- special attributes.</p>
99 --
100 -- @class table
101 -- @name format
102 format = {}
103
104 --- Return the string with a background color.
105 --
106 -- @param color the color to apply in background.
107 -- @param text the text to format.
108 -- @return The formatted text.
109 function format.set_bg(color, text)
110 return '<bg color="'..color..'" />'..text
111 end
112
113 --- Return the string with the given color.
114 --
115 -- @param color the color to apply on the text.
116 -- @param text the text to format.
117 -- @return The formatted text.
118 function format.set_fg(color, text)
119 return '<span color="'..color..'">'..text..'</span>'
120 end
121
122 --- Return the string with background and foreground color.
123 --
124 -- @param bgcolor the color to apply in background.
125 -- @param fgcolor the color to apply on the text.
126 -- @param text the text to format.
127 -- @return The formatted text.
128 function format.set_bg_fg(bgcolor, fgcolor, text)
129 return '<bg color="'..bgcolor..'" /><span color="'..fgcolor..'">'..text..'</span>'
130 end
131
132 --- Return the string with a defined font.
133 --
134 -- @param font the font to apply on the text.
135 -- @param text the text to format.
136 -- @return The formatted text.
137 function format.set_font(font, text)
138 return '<span font_desc="'..font..'">'..text..'</span>'
139 end
140
141 --- String related functions.
142 --
143 -- @class table
144 -- @name strings
145 strings = {}
146
147 --- Split the given string by whitespaces.
148 --
149 -- @param str the string to split.
150 -- @return a table with the string tokens.
151 function strings.split(str)
152 str = str or ''
153 values = {}
154
155 local start = 1
156 while true do
157 local splitstart, splitend = string.find(str, ' ', start)
158 local token = string.sub(str, start, splitstart and splitstart - 1 or nil)
159 if token:gsub(' ','') ~= '' then
160 table.insert(values, token)
161 end
162 if splitstart == nil then break end
163
164 start = splitend+1
165 splitstart, splitend = string.find(str, ' ', start)
166 end
167
168 return values
169 end
170
171 --- Crop the given string to the given maximum width.
172 --
173 -- <p>If string is too large, the right-most part is replaced by an
174 -- ellipsis.</p>
175 --
176 -- @param str the string to crop.
177 -- @param width the maximum result width.
178 -- @return the resulting string.
179 function strings.crop(str, width)
180 str = str or ''
181 local len = str:len()
182 width = width or len
183 if width < 3 then
184 str = ''
185 elseif len > width then
186 str = str:sub(1, width - 3) .. '...'
187 end
188 return str
189 end
190
191 --- Force a fixed width on the given string.
192 --
193 -- <p>If the string is too short, it is padded with spaces on the
194 -- left. If too long, it is cropped without an ellipsis.</p>
195 --
196 -- @param str the string to handle.
197 -- @param width the width to apply.
198 -- @return the resulting string.
199 function strings.pad_left(str, width)
200 str = str or ''
201 local len = str:len()
202 width = width or len
203 if width > len then
204 for i = 1, width - len do
205 str = ' ' .. str
206 end
207 else
208 str = str:sub(0, width)
209 end
210 return str
211 end
212
213 --- Force a fixed width on the given string.
214 --
215 -- <p>If the string is too short, it is padded with spaces on the
216 -- right. If too long, it is cropped without an ellipsis.</p>
217 --
218 -- @param str the string to handle.
219 -- @param width the width to apply.
220 -- @return the resulting string.
221 function strings.pad_right(str, width)
222 str = str or ''
223 local len = str:len()
224 width = width or len
225 if width > len then
226 for i = 1, width - len do
227 str = str .. ' '
228 end
229 else
230 str = str:sub(0, width)
231 end
232 return str
233 end
234
235 --- Pad a number to a minimum amount of digits.
236 --
237 -- <p>Caveat: the result is wrong for numbers between 0 and 1.</p>
238 --
239 -- @param str number the number to handle as a string.
240 -- @param padding the number of digits to add if necessary.
241 -- @return the resulting string.
242 function strings.pad_number(number, padding)
243 number = number or 0
244 local str = tostring(number) or ''
245 padding = padding or str:len()
246 for i = 1, padding do
247 if math.floor(number / math.pow(10, (i - 1))) == 0 then
248 str = '0' .. str
249 end
250 end
251 if number == 0 then
252 str = str:sub(2)
253 end
254 return str
255 end
256
257 --- Fill in a string with given arguments.
258 --
259 -- <p>This method replaces the $key patterns in the given string with
260 -- value got by indexing the given table with key.</p>
261 --
262 -- @param pattern the string to translate.
263 -- @param args the values table.
264 -- @return the resulting string.
265 function strings.format(pattern, args)
266 pattern = pattern or ''
267 args = args or {}
268 for key, value in pairs(args) do
269 if key ~= nil and value ~= nil then
270 pattern = string.gsub(pattern, '$' .. key, value)
271 end
272 end
273 return pattern
274 end
275
276 -- Convert amount of bytes to string.
277 function strings.format_bytes(bytes, padding)
278 bytes = bytes and tonumber(bytes) or ''
279 padding = padding
280 local sign = 1
281 while bytes / 1024 > 1 and unities[sign + 1] ~= nil do
282 bytes = bytes / 1024
283 sign = sign + 1
284 end
285 bytes = math.floor(bytes * 10)/10
286 if padding then
287 bytes = pad_number(bytes * 10, padding + 1)
288 bytes = bytes:sub(1, bytes:len() - 1) .. '.' .. bytes:sub(bytes:len())
289 end
290 return tostring(bytes) .. unities[sign]
291 end
292
293 --- Strip left spaces on a string.
294 --
295 -- @param str the string to handle.
296 -- @return the resulting string.
297 function strings.lstrip(str)
298 return str:match("^[ \t]*(.*)$")
299 end
300
301 --- Strip spaces on a string.
302 --
303 -- @param str the string to handle.
304 -- @return the resulting string.
305 function strings.strip(str)
306 return str:match("^[ \t]*(.-)[ \t]*$")
307 end
308
309 --- Strip right spaces on a string.
310 --
311 -- @param str the string to handle.
312 -- @return the resulting string.
313 function strings.rstrip(str)
314 return str:match("^(.-)[ \t]*$")
315 end
316
317 --- Escape a string
318 --
319 -- <p>This method replaces common URL-forbidden characters by their
320 -- HTML entity.</p>
321 --
322 -- @param text the string to handle.
323 -- @return the resulting string.
324 function strings.escape(text)
325 local xml_entities = {
326 ["\""] = "&quot;",
327 ["&"] = "&amp;",
328 ["'"] = "&apos;",
329 ["<"] = "&lt;",
330 [">"] = "&gt;"
331 }
332 return text and text:gsub("[\"&'<>]", xml_entities)
333 end
334
335 function round(n, p)
336 local m = 10^(p or 0)
337 return math.floor(m*n + 0.5)/m
338 end
339
340 --- Debug related tools.
341 --
342 -- @class table
343 -- @name debug
344 debug = {}
345
346 --- Display a message using a naughty notification.
347 --
348 -- @param message the message to display.
349 function debug.display(message)
350 naughty.notify{
351 title = "DEBUG",
352 text = tostring(message),
353 timeout = 5
354 }
355 end
356
357 --- Output a warning on error output.
358 --
359 -- @param message the message to log.
360 function debug.warn(message)
361 io.stderr:write(os.date('%A %d %B %H:%M:%S') .. ' WARNING: ' .. tostring(message) .. '\n')
362 end
363
364 --- Output an error on error output.
365 --
366 -- @param message the message to log.
367 function debug.error(message)
368 io.stderr:write(os.date('%A %d %B %H:%M:%S') .. ' ERROR: ' .. tostring(message) .. '\n')
369 end