about summary refs log blame commit diff stats
path: root/src/log.h
blob: 3e29e8ca782c16931370a1abc07df9f019637137 (plain) (tree)
1
2
3
4
5
6
  
        
                                 
  
                                                            
  












                                                                       
                                                                      
  











                                                                                

   


             
                 
 

                         







                     




                       
                                                  

                                 
                      
                                        



                                             
                                                                               
                                                   
 



                                        
                         
 



                                                                                                    
 



                                                 
 
                          

                              




                                                                                                          
 
      
/*
 * log.h
 * vim: expandtab:ts=4:sts=4:sw=4
 *
 * Copyright (C) 2012 - 2019 James Booth <boothj5@gmail.com>
 *
 * This file is part of Profanity.
 *
 * Profanity is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Profanity is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Profanity.  If not, see <https://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give permission to
 * link the code of portions of this program with the OpenSSL library under
 * certain conditions as described in each individual source file, and
 * distribute linked combinations including the two.
 *
 * You must obey the GNU General Public License in all respects for all of the
 * code used other than OpenSSL. If you modify file(s) with this exception, you
 * may extend this exception to your version of the file(s), but you are not
 * obligated to do so. If you do not wish to do so, delete this exception
 * statement from your version. If you delete this exception statement from all
 * source files in the program, then also delete it here.
 *
 */

#ifndef LOG_H
#define LOG_H

#include <glib.h>

#include "xmpp/message.h"

// log levels
typedef enum {
    PROF_LEVEL_DEBUG,
    PROF_LEVEL_INFO,
    PROF_LEVEL_WARN,
    PROF_LEVEL_ERROR
} log_level_t;

typedef enum {
    PROF_IN_LOG,
    PROF_OUT_LOG
} chat_log_direction_t;

void log_init(log_level_t filter, char *log_file);
log_level_t log_get_filter(void);
void log_close(void);
void log_reinit(void);
const char* get_log_file_location(void);
void log_debug(const char *const msg, ...);
void log_info(const char *const msg, ...);
void log_warning(const char *const msg, ...);
void log_error(const char *const msg, ...);
void log_msg(log_level_t level, const char *const area, const char *const msg);
log_level_t log_level_from_string(char *log_level);

void log_stderr_init(log_level_t level);
void log_stderr_close(void);
void log_stderr_handler(void);

void chat_log_init(void);

void chat_log_msg_out(const char *const barejid, const char *const msg, const char *resource);
void chat_log_otr_msg_out(const char *const barejid, const char *const msg, const char *resource);
void chat_log_pgp_msg_out(const char *const barejid, const char *const msg, const char *resource);
void chat_log_omemo_msg_out(const char *const barejid, const char *const msg, const char *resource);

void chat_log_msg_in(ProfMessage *message);
void chat_log_otr_msg_in(ProfMessage *message);
void chat_log_pgp_msg_in(ProfMessage *message);
void chat_log_omemo_msg_in(ProfMessage *message);

void chat_log_close(void);

void groupchat_log_init(void);

void groupchat_log_msg_out(const gchar *const room, const gchar *const msg);
void groupchat_log_msg_in(const gchar *const room, const gchar *const nick, const gchar *const msg);
void groupchat_log_omemo_msg_out(const gchar *const room, const gchar *const msg);
void groupchat_log_omemo_msg_in(const gchar *const room, const gchar *const nick, const gchar *const msg);

#endif
span> ^
ee4687c3 ^


39db95d9 ^







e5c44775 ^


ee4687c3 ^
39db95d9 ^



e5c44775 ^
39db95d9 ^


d8cd2b75 ^
4ba2112b ^
cfe081ec ^

4ba2112b ^
ee4687c3 ^

4ba2112b ^






ee4687c3 ^

4ba2112b ^








ca909b9a ^
cfe081ec ^

ca909b9a ^

ee4687c3 ^


ca909b9a ^



cfe081ec ^
d6429e27 ^

ca909b9a ^




cfe081ec ^

ca909b9a ^

e5c44775 ^
cfe081ec ^

e5c44775 ^





ee4687c3 ^



e5c44775 ^

13ecffe7 ^










e5c44775 ^

ee4687c3 ^
e5c44775 ^





ee4687c3 ^
e5c44775 ^


c70c915b ^

e975b52f ^

c70c915b ^

e975b52f ^

c70c915b ^

e5c44775 ^
d8cd2b75 ^
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
              


                                                            

                                     
 
          
 

                                                     








                                                                                    

                                                                              


                                                  














                                                                                    











                                                                



                                                          













                                                         
























                                                                                        


                                                                






                                









                                                  


                                                           

                               





                                                  

                                


                                                               



















                                                               

                            







                                                                              

                                       
                                                           
                                                                











                                                                
 
                                   
















                                            
                                           





















                                                       

                              




                                                  
                                                 

                                               
                                                                  
















                                                            
 
                           
                            
                                                   
                                                        
                                

                                


                                                       

                                  

                                     
                                              






                                                                
                                 
                                             
                                               

                                                      

                                 

                                     
                                              

                                                           





                                                                           

                                     
 
                                             
 
                                                   
                                                  


                                                    

                                                                                 
                                                   
                                                     
                                                  
 

                                       
 

                                                                   
 
                                                  




                                                                       
 
                               

                                     
                                              

                                                           
 
                                                                
 

                                                        
                                                                       
 


                                                       







                                                                


                                                                                    
                                                   



                                                              
                                                      


                                                        
 
                                           

                                     
                                              

                                                           






                                                  

                                                            








                                                                       
                                   

                                     

                                              


                                                           



                                                 
                                                  

                                         




                                                    

                                                                                   

                          
                                               

                                     





                                                 



                                                           

                                               










                                                

                                                
                                                  





                                                    
                                                         


                                                     

                                      

                                  

                                                  

                                     

                                                     
 
                                 
# coding=utf-8
if __name__ == '__main__': from __init__ import init; init()
from unittest import TestCase, main

from ranger.ext.tree import Tree
from ranger.container.keymap import *

import sys

class PressTestCase(TestCase):
	"""Some useful methods for the actual test"""
	def _mkpress(self, keybuffer, keymap):
		def press(keys):
			keybuffer.clear()
			match = keybuffer.simulate_press(keys)
			self.assertFalse(keybuffer.failure,
					"parsing keys '"+keys+"' did fail!")
			self.assertTrue(keybuffer.done,
					"parsing keys '"+keys+"' did not complete!")
			arg = CommandArgs(None, None, keybuffer)
			self.assert_(match.function, "No function found! " + \
					str(match.__dict__))
			return match.function(arg)
		return press

	def assertPressFails(self, kb, keys):
		kb.clear()
		kb.simulate_press(keys)
		self.assertTrue(kb.failure, "Keypress did not fail as expected")
		kb.clear()

	def assertPressIncomplete(self, kb, keys):
		kb.clear()
		kb.simulate_press(keys)
		self.assertFalse(kb.failure, "Keypress failed, expected incomplete")
		self.assertFalse(kb.done, "Keypress done which was unexpected")
		kb.clear()

class Test(PressTestCase):
	"""The test cases"""
	def test_passive_action(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		def n(value):
			"""return n or value"""
			def fnc(arg=None):
				if arg is None or arg.n is None:
					return value
				return arg.n
			return fnc

		km.map('ppp', n(5))
		km.map('pp<psv>', n(8))
		km.map('pp<dir>', n(2))
		directions.map('j', dir=Direction(down=1))

		press = self._mkpress(kb, km)
		self.assertEqual(5, press('ppp'))
		self.assertEqual(3, press('3ppp'))

		self.assertEqual(2, press('ppj'))

		kb.clear()
		match = kb.simulate_press('pp')
		args = CommandArgs(0, 0, kb)
		self.assert_(match)
		self.assert_(match.function)
		self.assertEqual(8, match.function(args))

	def test_translate_keys(self):
		def test(string, *args):
			if not args:
				args = (string, )
			self.assertEqual(ordtuple(*args), tuple(translate_keys(string)))

		def ordtuple(*args):
			lst = []
			for arg in args:
				if isinstance(arg, str):
					lst.extend(ord(c) for c in arg)
				else:
					lst.append(arg)
			return tuple(lst)

		test('k')
		test('kj')
		test('k<dir>', 'k', DIRKEY)
		test('k<ANY>z<any>', 'k', ANYKEY, 'z', ANYKEY)
		test('k<anY>z<dir>', 'k', ANYKEY, 'z', DIRKEY)
		test('<cr>', "\n")
		test('<tab><tab><cr>', "\t\t\n")
		test('<')
		test('>')
		test('<C-a>', 1)
		test('<C-b>', 2)
		for i in range(1, 26):
			test('<C-' + chr(i+ord('a')-1) + '>', i)
		test('k<a')
		test('k<anz>')
		test('k<a<nz>')
		test('k<a<nz>')
		test('k<a<>nz>')
		test('>nz>')

	def test_alias(self):
		def add_dirs(arg):
			n = 0
			for dir in arg.directions:
				n += dir.down
			return n
		def return5(_):
			return 5

		directions = KeyMap()
		directions.map('j', dir=Direction(down=1))
		directions.map('k', dir=Direction(down=-1))
		directions.map('<CR>', alias='j')

		base = KeyMap()
		base.map('a<dir>', add_dirs)
		base.map('b<dir>', add_dirs)
		base.map('x<dir>x<dir>', add_dirs)
		base.map('f', return5)
		base.map('yy', alias='y')
		base.map('!', alias='!')

		other = KeyMap()
		other.map('b<dir>b<dir>', alias='x<dir>x<dir>')
		other.map('c<dir>', add_dirs)
		other.map('g', alias='f')

		km = base.merge(other)
		kb = KeyBuffer(km, directions)

		press = self._mkpress(kb, km)

		self.assertEqual(1, press('aj'))
		self.assertEqual(2, press('bjbj'))
		self.assertEqual(1, press('cj'))
		self.assertEqual(1, press('c<CR>'))

		self.assertEqual(5, press('f'))
		self.assertEqual(5, press('g'))

		for n in range(1, 50):
			self.assertPressIncomplete(kb, 'y' * n)

		for n in range(1, 5):
			self.assertPressFails(kb, '!' * n)

	def test_tree(self):
		t = Tree()
		t.set('abcd', "Yes")
		self.assertEqual("Yes", t.traverse('abcd'))
		self.assertRaises(KeyError, t.traverse, 'abcde')
		self.assertRaises(KeyError, t.traverse, 'xyz')
		self.assert_(isinstance(t.traverse('abc'), Tree))

		t2 = Tree()
		self.assertRaises(KeyError, t2.set, 'axy', "Lol", force=False)
		t2.set('axx', 'ololol')
		t2.set('axyy', "Lol")
		self.assertEqual("Yes", t.traverse('abcd'))
		self.assertRaises(KeyError, t2.traverse, 'abcd')
		self.assertEqual("Lol", t2.traverse('axyy'))
		self.assertEqual("ololol", t2.traverse('axx'))

		t2.unset('axyy')
		self.assertEqual("ololol", t2.traverse('axx'))
		self.assertRaises(KeyError, t2.traverse, 'axyy')
		self.assertRaises(KeyError, t2.traverse, 'axy')

		t2.unset('a')
		self.assertRaises(KeyError, t2.traverse, 'abcd')
		self.assertRaises(KeyError, t2.traverse, 'a')
		self.assert_(t2.empty())

	def test_merge_trees(self):
		def makeTreeA():
			t = Tree()
			t.set('aaaX', 1)
			t.set('aaaY', 2)
			t.set('aaaZ', 3)
			t.set('bbbA', 11)
			t.set('bbbB', 12)
			t.set('bbbC', 13)
			t.set('bbbD', 14)
			t.set('bP', 21)
			t.set('bQ', 22)
			return t

		def makeTreeB():
			u = Tree()
			u.set('aaaX', 0)
			u.set('bbbC', 'Yes')
			u.set('bbbD', None)
			u.set('bbbE', 15)
			u.set('bbbF', 16)
			u.set('bQ', 22)
			u.set('bR', 23)
			u.set('ffff', 1337)
			return u

		# test 1
		t = Tree('a')
		u = Tree('b')
		merged = t.merge(u)
		self.assertEqual('b', merged._tree)

		# test 2
		t = Tree('a')
		u = makeTreeA()
		merged = t.merge(u)
		self.assertEqual(u._tree, merged._tree)

		# test 3
		t = makeTreeA()
		u = makeTreeB()
		v = t.merge(u)

		self.assertEqual(0, v['aaaX'])
		self.assertEqual(2, v['aaaY'])
		self.assertEqual(3, v['aaaZ'])
		self.assertEqual(11, v['bbbA'])
		self.assertEqual('Yes', v['bbbC'])
		self.assertEqual(None, v['bbbD'])
		self.assertEqual(15, v['bbbE'])
		self.assertEqual(16, v['bbbF'])
		self.assertRaises(KeyError, t.__getitem__, 'bbbG')
		self.assertEqual(21, v['bP'])
		self.assertEqual(22, v['bQ'])
		self.assertEqual(23, v['bR'])
		self.assertEqual(1337, v['ffff'])

		# merge shouldn't be destructive
		self.assertEqual(makeTreeA()._tree, t._tree)
		self.assertEqual(makeTreeB()._tree, u._tree)

		v['fff'].replace('Lolz')
		self.assertEqual('Lolz', v['fff'])

		v['aaa'].replace('Very bad')
		v.plow('qqqqqqq').replace('eww.')

		self.assertEqual(makeTreeA()._tree, t._tree)
		self.assertEqual(makeTreeB()._tree, u._tree)

	def test_add(self):
		c = KeyMap()
		c.map('aa', 'b', lambda *_: 'lolz')
		self.assert_(c['aa'].function(), 'lolz')
		@c.map('a', 'c')
		def test():
			return 5
		self.assert_(c['b'].function(), 'lolz')
		self.assert_(c['c'].function(), 5)
		self.assert_(c['a'].function(), 5)

	def test_quantifier(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		def n(value):
			"""return n or value"""
			def fnc(arg=None):
				if arg is None or arg.n is None:
					return value
				return arg.n
			return fnc
		km.map('p', n(5))
		press = self._mkpress(kb, km)
		self.assertEqual(5, press('p'))
		self.assertEqual(3, press('3p'))
		self.assertEqual(6223, press('6223p'))

	def test_direction(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		directions.map('j', dir=Direction(down=1))
		directions.map('k', dir=Direction(down=-1))
		def nd(arg):
			""" n * direction """
			n = arg.n is None and 1 or arg.n
			dir = arg.direction is None and Direction(down=1) \
					or arg.direction
			return n * dir.down
		km.map('d<dir>', nd)
		km.map('dd', func=nd)

		press = self._mkpress(kb, km)

		self.assertPressIncomplete(kb, 'd')
		self.assertEqual(  1, press('dj'))
		self.assertEqual(  3, press('3ddj'))
		self.assertEqual( 15, press('3d5j'))
		self.assertEqual(-15, press('3d5k'))
		# supporting this kind of key combination would be too confusing:
		# self.assertEqual( 15, press('3d5d'))
		self.assertEqual(  3, press('3dd'))
		self.assertEqual(  33, press('33dd'))
		self.assertEqual(  1, press('dd'))

		km.map('x<dir>', nd)
		km.map('xxxx', func=nd)

		self.assertEqual(1, press('xxxxj'))
		self.assertEqual(1, press('xxxxjsomeinvalitchars'))

		# these combinations should break:
		self.assertPressFails(kb, 'xxxj')
		self.assertPressFails(kb, 'xxj')
		self.assertPressFails(kb, 'xxkldfjalksdjklsfsldkj')
		self.assertPressFails(kb, 'xyj')
		self.assertPressIncomplete(kb, 'x') # direction missing

	def test_any_key(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		directions.map('j', dir=Direction(down=1))
		directions.map('k', dir=Direction(down=-1))

		directions.map('g<any>', dir=Direction(down=-1))

		def cat(arg):
			n = arg.n is None and 1 or arg.n
			return ''.join(chr(c) for c in arg.matches) * n

		km.map('return<any>', cat)
		km.map('cat4<any><any><any><any>', cat)
		km.map('foo<dir><any>', cat)

		press = self._mkpress(kb, km)

		self.assertEqual('x', press('returnx'))
		self.assertEqual('abcd', press('cat4abcd'))
		self.assertEqual('abcdabcd', press('2cat4abcd'))
		self.assertEqual('55555', press('5return5'))

		self.assertEqual('x', press('foojx'))
		self.assertPressFails(kb, 'fooggx')  # ANYKEY forbidden in DIRECTION

		km.map('<any>', lambda _: Ellipsis)
		self.assertEqual('x', press('returnx'))
		self.assertEqual('abcd', press('cat4abcd'))
		self.assertEqual(Ellipsis, press('2cat4abcd'))
		self.assertEqual(Ellipsis, press('5return5'))
		self.assertEqual(Ellipsis, press('g'))
		self.assertEqual(Ellipsis, press('ß'))
		self.assertEqual(Ellipsis, press('ア'))
		self.assertEqual(Ellipsis, press('9'))

	def test_multiple_directions(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		directions.map('j', dir=Direction(down=1))
		directions.map('k', dir=Direction(down=-1))

		def add_dirs(arg):
			n = 0
			for dir in arg.directions:
				n += dir.down
			return n

		km.map('x<dir>y<dir>', add_dirs)
		km.map('four<dir><dir><dir><dir>', add_dirs)

		press = self._mkpress(kb, km)

		self.assertEqual(2, press('xjyj'))
		self.assertEqual(0, press('fourjkkj'))
		self.assertEqual(2, press('four2j4k2j2j'))
		self.assertEqual(10, press('four1j2j3j4j'))
		self.assertEqual(10, press('four1j2j3j4jafslkdfjkldj'))

	def test_corruptions(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		press = self._mkpress(kb, km)
		directions.map('j', dir=Direction(down=1))
		directions.map('k', dir=Direction(down=-1))
		km.map('xxx', lambda _: 1)

		self.assertEqual(1, press('xxx'))

		# corrupt the tree
		tup = tuple(translate_keys('xxx'))
		x = ord('x')
		km._tree[x][x][x] = "Boo"

		self.assertPressFails(kb, 'xxy')
		self.assertPressFails(kb, 'xzy')
		self.assertPressIncomplete(kb, 'xx')
		self.assertPressIncomplete(kb, 'x')
		if not sys.flags.optimize:
			self.assertRaises(AssertionError, kb.simulate_press, 'xxx')
		kb.clear()

	def test_directions_as_functions(self):
		km = KeyMap()
		directions = KeyMap()
		kb = KeyBuffer(km, directions)
		press = self._mkpress(kb, km)

		def move(arg):
			return arg.direction.down

		directions.map('j', dir=Direction(down=1))
		directions.map('s', alias='j')
		directions.map('k', dir=Direction(down=-1))
		km.map('<dir>', func=move)

		self.assertEqual(1, press('j'))
		self.assertEqual(1, press('j'))
		self.assertEqual(1, press('j'))
		self.assertEqual(1, press('j'))
		self.assertEqual(1, press('j'))
		self.assertEqual(1, press('s'))
		self.assertEqual(1, press('s'))
		self.assertEqual(1, press('s'))
		self.assertEqual(1, press('s'))
		self.assertEqual(1, press('s'))
		self.assertEqual(-1, press('k'))
		self.assertEqual(-1, press('k'))
		self.assertEqual(-1, press('k'))

		km.map('k', func=lambda _: 'love')

		self.assertEqual(1, press('j'))
		self.assertEqual('love', press('k'))

		self.assertEqual(40, press('40j'))

		km.map('<dir><dir><any><any>', func=move)

		self.assertEqual(40, press('40jkhl'))

	def test_tree_deep_copy(self):
		t = Tree()
		s = t.plow('abcd')
		s.replace('X')
		u = t.copy()
		self.assertEqual(t._tree, u._tree)
		s = t.traverse('abc')
		s.replace('Y')
		self.assertNotEqual(t._tree, u._tree)


if __name__ == '__main__': main()