Debian Codegraph @

src/backend/plugins/PluginBase.py

raw symbols SCIP
1 # Copyright (c) 2010 Anil Kumar
2 # All rights reserved.
3 #
4 # License: BSD
5
6 import os, re
7 import copy
8
9 from PyQt6.QtCore import QObject, pyqtSignal, QProcess
10
11 def NOT_IMPLEMENTED(n, f):
12 msg = '%s: %s: Not implemeted' % (n, f)
13 from PyQt6.QtWidgets import QMessageBox
14 QMessageBox.warning(None, "Seascope", msg, QMessageBox.StandardButton.Ok)
15
16 from . import CtagsCache
17
18 cmd_table_master = [
19 [ 'REF', ['&References', 'Ctrl+0'], ['References to' ] ],
20 [ 'DEF', ['&Definitions', 'Ctrl+1'], ['Definition of' ] ],
21 [ '<--', ['&Called Functions', 'Ctrl+2'], ['Functions called by' ] ],
22 [ '-->', ['C&alling Functions', 'Ctrl+3'], ['Functions calling' ] ],
23 [ 'TXT', ['Find &Text', 'Ctrl+4'], ['Find text' ] ],
24 [ 'GREP', ['Find &Egrep', 'Ctrl+5'], ['Find egrep pattern' ] ],
25 [ 'FIL', ['Find &File', 'Ctrl+7'], ['Find files' ] ],
26 [ 'INC', ['&Include/Import', 'Ctrl+8'], ['Find include/import' ] ],
27 [ '---', [None, ], None ],
28 [ 'QDEF', ['&Quick Definition', 'Ctrl+]'], None ],
29 [ 'CTREE', ['Call Tr&ee', 'Ctrl+\\'], ['Call tree' ] ],
30 [ '---', [None, ], None ],
31 [ 'CLGRAPH', ['Class &Graph', 'Ctrl+:'], ['Class graph' ] ],
32 [ 'CLGRAPHD', ['Class Graph Dir', 'Ctrl+;'], ['Class graph dir' ] ],
33 [ 'FFGRAPH', ['File Func Graph', 'Ctrl+^'], ['File Func graph dir' ] ],
34 [ '---', [None, ], None ],
35 [ 'UPD', ['Re&build Database', None ], None ],
36 ]
37 class PluginFeatureBase:
38 def __init__(self):
39 self.clgraph_query_args = [
40 ['CLGRAPH', 'D', 'Derived classes' ],
41 ['CLGRAPH', 'B', 'Base classes' ],
42 ]
43 self.clgraph_query_args = [
44 ['CLGRAPH', 'D', 'Derived classes' ],
45 ['CLGRAPH', 'B', 'Base classes' ],
46 ]
47 self.ffgraph_query_args = [
48 ['FFGRAPH', 'F', 'File functions graph'],
49 ['FFGRAPH_E', 'F+E', 'File functions + external graph'],
50 ['FFGRAPH_D', 'D', 'Directory functions graph'],
51 ['FFGRAPH_DE', 'D+E', 'Directory functions + external graph']
52 ]
53
54 def setup(self):
55 feat_cmds = [ d[0] for d in self.feat_desc ]
56 ct = copy.deepcopy(cmd_table_master)
57 self.cmd_table = [ t for t in ct if t[0] in feat_cmds or t[0] == '---' ]
58
59 self.menu_cmd_list = [ [c[0]] + c[1] for c in self.cmd_table ]
60
61 self.cmd_str2id = {}
62 self.cmd_str2qstr = {}
63 self.cmd_qstr2str = {}
64 for c in self.feat_desc:
65 self.cmd_str2id[c[0]] = c[1]
66 for c in self.cmd_table:
67 if c[2] != None:
68 self.cmd_str2qstr[c[0]] = c[2][0]
69 self.cmd_qstr2str[c[2][0]] = c[0]
70 # python 2.7
71 #self.cmd_str2id = { c[0]:c[1] for c in self.feat_desc }
72 #self.cmd_str2qstr = { c[0]:c[2][0] for c in self.cmd_table if c[1] }
73 #self.cmd_qstr2str = { c[2][0]:c[0] for c in self.cmd_table if c[1] }
74 self.cmd_qstrlist = [ c[2][0] for c in self.cmd_table if c[2] ]
75
76 class ProjectBase(QObject):
77 prj = None
78 qry = None
79
80 def __init__(self):
81 QObject.__init__(self)
82 self.feat = None
83
84 def prj_close(self):
85 if (self.conf != None):
86 self.conf.proj_close()
87 self.conf = None
88
89 def prj_dir(self):
90 return self.conf.c_dir
91 def prj_name(self):
92 return self.conf.get_proj_name()
93 def prj_src_files(self):
94 return self.conf.get_proj_src_files()
95
96 def prj_is_open(self):
97 return self.conf != None
98 def prj_is_ready(self):
99 return self.conf.is_ready()
100
101 def prj_conf(self):
102 return self.conf.get_proj_conf()
103
104 def prj_update_conf(self, proj_args):
105 self.conf.proj_update(proj_args)
106
107 def prj_show_settings(self, proj_args):
108 NOT_IMPLEMENTED(__name__, __func__)
109 def prj_settings(self, proj_args):
110 NOT_IMPLEMENTED(__name__, __func__)
111
112 def prj_feature_setup(self):
113 self.feat.setup()
114
115 def prj_query(self, rquery):
116 return self.qry.query(rquery)
117
118 def prj_rebuild(self):
119 return self.qry.rebuild()
120
121 def prj_query_fl(self):
122 return self.qry.query_fl()
123
124 def prj_type(self):
125 return self.conf.prj_type
126
127 def prj_feature(self):
128 return self.feat
129
130 def prj_settings_get(self):
131 proj_args = self.prj_conf()
132 return proj_args
133
134 def prj_settings_update(self, proj_args):
135 NOT_IMPLEMENTED(__name__, __func__)
136 return
137
138 class ConfigBase(QObject):
139 def __init__(self, ptype):
140 self.prj_type = ptype
141 self.c_dir = ''
142 self.c_opt = ''
143 self.c_flist = []
144
145 def get_proj_name(self):
146 return os.path.split(self.c_dir)[1]
147
148 def get_proj_src_files(self):
149 fl = self.c_flist
150 return fl
151
152 def get_proj_conf(self):
153 return (self.c_dir, self.c_opt, self.c_flist)
154
155 def read_config(self):
156 pass
157 def write_config(self):
158 pass
159
160 def proj_start(self):
161 pass
162
163 def proj_open(self, proj_path):
164 self.c_dir = proj_path
165 self.read_config()
166 self.proj_start()
167
168 def proj_update(self, proj_args):
169 self.proj_new(proj_args)
170
171 def proj_new(self, proj_args):
172 self.proj_args = proj_args
173 (self.c_dir, self.c_opt, self.c_flist) = proj_args
174 self.write_config()
175 self.proj_start()
176
177 def proj_close(self):
178 pass
179
180 def is_ready(self):
181 return True
182
183 @staticmethod
184 def prepare_menu(menubar):
185 pass
186
187 class QueryBase(QObject):
188 @staticmethod
189 def prepare_menu(menubar):
190 pass
191
192 def query(self, rquery):
193 cmd_str = rquery['cmd']
194 req = rquery['req']
195 opt = rquery['opt']
196 if opt == None:
197 opt = []
198
199 pargs = []
200 if cmd_str == 'GREP':
201 pargs = ['grep', '-E', '-R', '-n', '-I']
202 pargs += [ '--', req ]
203 pargs += [self.conf.c_dir]
204 else:
205 assert(false)
206 return None
207 qsig = PluginProcess(self.conf.c_dir, [cmd_str, req]).run_query_process(pargs, req, rquery)
208 return qsig
209
210 def rebuild():
211 NOT_IMPLEMENTED(__name__, __func__)
212
213 def conf_is_open(self):
214 return self.conf != None
215 def conf_is_ready(self):
216 return self.conf.is_ready()
217
218
219 class QueryUiBase(QObject):
220 def __init__(self):
221 QObject.__init__(self)
222
223 from PyQt6.QtWidgets import QMessageBox
224
225 class QuerySignal(QObject):
226 sig_result = pyqtSignal(str, list)
227 sig_result_dbg = pyqtSignal(str, str, str)
228 sig_rebuild = pyqtSignal()
229 sig_query_fl = pyqtSignal(list)
230
231 def __init__(self):
232 QObject.__init__(self)
233
234 def _relevancy_sort(self, hfile, res):
235 pt = []
236 pd = {}
237 p = hfile
238 (pre, ext) = os.path.splitext(hfile)
239 c = None
240 while p != c:
241 e = [p, [], []]
242 pt += [e]
243 pd[p] = e
244 c = p
245 p = os.path.dirname(p)
246 for line in res:
247 f = line[1]
248 d = os.path.dirname(f)
249 p = f
250 while p not in pd:
251 p = os.path.dirname(p)
252 e = pd[p]
253 if p in [f, d]:
254 e[1].append(line)
255 else:
256 e[2].append(line)
257 for e in pt:
258 e[1] = sorted(e[1], key=lambda li: li[1])
259 e[2] = sorted(e[2], key=lambda li: li[1])
260 pre = pre + '.*'
261 e0 = []
262 e1 = []
263 for e in pt[1][1]:
264 if re.match(pre, e[1]):
265 e0 += [e]
266 else:
267 e1 += [e]
268 pt[0][1] += e0
269 pt[1][1] = e1
270
271 res1 = []
272 res2 = []
273 for e in pt:
274 res1 += e[1]
275 res2 += e[2]
276 res = res1 + res2
277 return res
278
279 def relevancy_sort(self, res):
280 if os.getenv('RELEVANCY_SORT', 1) == 0:
281 return res
282 hint_file = None
283 try:
284 hint_file = self.rquery['hint_file']
285 except:
286 pass
287 if not hint_file:
288 return res
289 if not os.path.isabs(hint_file):
290 print('BUG: relevancy_sort: not abs path:', hint_file)
291 return res
292 if len(res) > 10000:
293 return res
294 return self._relevancy_sort(hint_file, res)
295
296 def emit_result(self, res):
297 res = self.relevancy_sort(res)
298 self.sig_result.emit(self.sym, res)
299
300 class PluginProcessBase(QObject):
301 proc_list = []
302
303 def __init__(self, wdir):
304 QObject.__init__(self)
305
306 PluginProcess.proc_list.append(self)
307 self.is_rebuild = False
308 self.is_query_fl = False
309
310 self.sig = QuerySignal()
311
312 self.proc = QProcess()
313 self.proc.finished.connect(self._finished_cb)
314 self.proc.errorOccurred.connect(self._error_cb)
315
316 self.proc.setWorkingDirectory(wdir)
317 self.wdir = wdir
318
319 def _cleanup(self):
320 PluginProcess.proc_list.remove(self)
321 if self.err_str != '':
322 s = '<b>' + self.p_cmd + '</b><p>' + '<p>'.join(self.err_str.splitlines())
323 QMessageBox.warning(None, "Seascope", s, QMessageBox.StandardButton.Ok)
324 if self.res != '':
325 s = '<b>' + self.p_cmd + '</b><p>Summary<p>' + self.res
326 QMessageBox.information(None, "Seascope", s, QMessageBox.StandardButton.Ok)
327
328 def _error_cb(self, err):
329 err_dict = {
330 QProcess.ProcessError.FailedToStart: 'FailedToStart',
331 QProcess.ProcessError.Crashed: 'Crashed',
332 QProcess.ProcessError.Timedout: 'The last waitFor...() function timed out',
333 QProcess.ProcessError.WriteError: 'An error occurred when attempting to write to the process',
334 QProcess.ProcessError.ReadError: 'An error occurred when attempting to read from the process',
335 QProcess.ProcessError.UnknownError: 'An unknown error occurred',
336 }
337 self.err_str = '<b>' + self.p_cmd + '</b><p>' + err_dict[err]
338 self._cleanup()
339
340 def _finished_cb(self, ret):
341 res = self.proc.readAllStandardOutput().data().decode()
342 self.err_str = self.proc.readAllStandardError().data().decode()
343
344 #print 'output', res
345 #print 'cmd:', self.p_cmd
346 if self.is_rebuild:
347 self.res = res
348 self.sig.sig_rebuild.emit()
349 elif self.is_query_fl:
350 self.res = ''
351 res = self.parse_query_fl(res)
352 self.sig.sig_query_fl.emit(res)
353 else:
354 self.res = ''
355 self.sig.sig_result_dbg.emit(self.p_cmd, res, self.err_str)
356 try:
357 res = self.parse_result(res, self.sig)
358 except Exception as e:
359 print(e)
360 res = [['', '', '', 'error while parsing output of: ' + self.p_cmd]]
361 if res != None:
362 self.sig.emit_result(res)
363
364 self._cleanup()
365
366 def run_query_process(self, pargs, sym, rquery=None):
367 self.sig.sym = sym
368 self.sig.rquery = rquery
369 self.p_cmd = ' '.join(pargs)
370 if os.getenv('SEASCOPE_DEBUG'):
371 print(self.p_cmd)
372 self.proc.start(pargs[0], pargs[1:])
373 if self.proc.waitForStarted() == False:
374 return None
375 self.proc.closeWriteChannel()
376 return [self.sig.sig_result, self.sig.sig_result_dbg]
377
378 def run_rebuild_process(self, pargs):
379 self.is_rebuild = True
380 self.p_cmd = ' '.join(pargs)
381 self.proc.start(pargs[0], pargs[1:])
382 if self.proc.waitForStarted() == False:
383 return None
384 #print 'cmd:', pargs
385 self.sig.sig_rebuild.connect(CtagsCache.flush)
386 return self.sig.sig_rebuild
387
388 def run_query_fl(self, pargs):
389 self.is_query_fl = True
390 self.p_cmd = ' '.join(pargs)
391 self.proc.start(pargs[0], pargs[1:])
392 if self.proc.waitForStarted() == False:
393 return None
394 return self.sig.sig_query_fl
395
396 def parse_query_fl(self, text):
397 fl = []
398 for f in re.split(r'\r?\n', text.strip()):
399 if f == '':
400 continue
401 fl.append(os.path.join(self.wdir, f))
402 return fl
403
404 class PluginProcess(PluginProcessBase):
405 def __init__(self, wdir, rq):
406 PluginProcessBase.__init__(self, wdir)
407 if rq == None:
408 rq = ['', '']
409 self.cmd_str = rq[0]
410 self.req = rq[1]
411
412 def parse_result(self, text, sig):
413 text = re.split(r'\r?\n', text)
414
415 res = []
416 if self.cmd_str == 'GREP':
417 for line in text:
418 if line == '':
419 continue
420 line = ['<unknown>'] + line.split(':', 2)
421 res.append(line)
422 else:
423 assert(false)
424 res.append(['', '', '', 'PluginProcess.parse_result: FAILED'])
425 return res
426
427 qsig = CtagsCache.CtagsThread(sig).apply_fix(self.cmd_str, res, ['<unknown>'])
428 return qsig
429
430 if __name__ == '__main__':
431 import sys
432
433 def slot_result(sym, res):
434 print('slot_result: ', [str(sym), res])
435 sys.exit(0)
436 def slot_result_dbg(cmd, res, err_str):
437 err_str = err_str.decode()
438 print('slot_result_dbg:', [str(cmd), str(res).strip().split('\n'), str(err_str)])
439 def slot_rebuild():
440 print('slot_rebuild')
441
442 from PyQt6.QtCore import QCoreApplication
443 app = QCoreApplication(sys.argv)
444
445 qsig = PluginProcess('.').run_query_process(['ls'], 'ls')
446 #qsig = PluginProcess('/home/anil/prj/ss/lin').run_query_process(['cscope', '-q', '-k', '-L', '-d', '-0', 'vdso'], 'ls')
447 if qsig == None:
448 sys.exit(-1)
449 qsig[0].connect(slot_result)
450 qsig[1].connect(slot_result_dbg)
451
452 app.exec()