exported-sql-viewer.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. #!/usr/bin/python2
  2. # SPDX-License-Identifier: GPL-2.0
  3. # exported-sql-viewer.py: view data from sql database
  4. # Copyright (c) 2014-2018, Intel Corporation.
  5. # To use this script you will need to have exported data using either the
  6. # export-to-sqlite.py or the export-to-postgresql.py script. Refer to those
  7. # scripts for details.
  8. #
  9. # Following on from the example in the export scripts, a
  10. # call-graph can be displayed for the pt_example database like this:
  11. #
  12. # python tools/perf/scripts/python/exported-sql-viewer.py pt_example
  13. #
  14. # Note that for PostgreSQL, this script supports connecting to remote databases
  15. # by setting hostname, port, username, password, and dbname e.g.
  16. #
  17. # python tools/perf/scripts/python/exported-sql-viewer.py "hostname=myhost username=myuser password=mypassword dbname=pt_example"
  18. #
  19. # The result is a GUI window with a tree representing a context-sensitive
  20. # call-graph. Expanding a couple of levels of the tree and adjusting column
  21. # widths to suit will display something like:
  22. #
  23. # Call Graph: pt_example
  24. # Call Path Object Count Time(ns) Time(%) Branch Count Branch Count(%)
  25. # v- ls
  26. # v- 2638:2638
  27. # v- _start ld-2.19.so 1 10074071 100.0 211135 100.0
  28. # |- unknown unknown 1 13198 0.1 1 0.0
  29. # >- _dl_start ld-2.19.so 1 1400980 13.9 19637 9.3
  30. # >- _d_linit_internal ld-2.19.so 1 448152 4.4 11094 5.3
  31. # v-__libc_start_main@plt ls 1 8211741 81.5 180397 85.4
  32. # >- _dl_fixup ld-2.19.so 1 7607 0.1 108 0.1
  33. # >- __cxa_atexit libc-2.19.so 1 11737 0.1 10 0.0
  34. # >- __libc_csu_init ls 1 10354 0.1 10 0.0
  35. # |- _setjmp libc-2.19.so 1 0 0.0 4 0.0
  36. # v- main ls 1 8182043 99.6 180254 99.9
  37. #
  38. # Points to note:
  39. # The top level is a command name (comm)
  40. # The next level is a thread (pid:tid)
  41. # Subsequent levels are functions
  42. # 'Count' is the number of calls
  43. # 'Time' is the elapsed time until the function returns
  44. # Percentages are relative to the level above
  45. # 'Branch Count' is the total number of branches for that function and all
  46. # functions that it calls
  47. import sys
  48. import weakref
  49. import threading
  50. import string
  51. from PySide.QtCore import *
  52. from PySide.QtGui import *
  53. from PySide.QtSql import *
  54. from decimal import *
  55. # Data formatting helpers
  56. def dsoname(name):
  57. if name == "[kernel.kallsyms]":
  58. return "[kernel]"
  59. return name
  60. # Percent to one decimal place
  61. def PercentToOneDP(n, d):
  62. if not d:
  63. return "0.0"
  64. x = (n * Decimal(100)) / d
  65. return str(x.quantize(Decimal(".1"), rounding=ROUND_HALF_UP))
  66. # Helper for queries that must not fail
  67. def QueryExec(query, stmt):
  68. ret = query.exec_(stmt)
  69. if not ret:
  70. raise Exception("Query failed: " + query.lastError().text())
  71. # Background thread
  72. class Thread(QThread):
  73. done = Signal(object)
  74. def __init__(self, task, param=None, parent=None):
  75. super(Thread, self).__init__(parent)
  76. self.task = task
  77. self.param = param
  78. def run(self):
  79. while True:
  80. if self.param is None:
  81. done, result = self.task()
  82. else:
  83. done, result = self.task(self.param)
  84. self.done.emit(result)
  85. if done:
  86. break
  87. # Tree data model
  88. class TreeModel(QAbstractItemModel):
  89. def __init__(self, root, parent=None):
  90. super(TreeModel, self).__init__(parent)
  91. self.root = root
  92. self.last_row_read = 0
  93. def Item(self, parent):
  94. if parent.isValid():
  95. return parent.internalPointer()
  96. else:
  97. return self.root
  98. def rowCount(self, parent):
  99. result = self.Item(parent).childCount()
  100. if result < 0:
  101. result = 0
  102. self.dataChanged.emit(parent, parent)
  103. return result
  104. def hasChildren(self, parent):
  105. return self.Item(parent).hasChildren()
  106. def headerData(self, section, orientation, role):
  107. if role == Qt.TextAlignmentRole:
  108. return self.columnAlignment(section)
  109. if role != Qt.DisplayRole:
  110. return None
  111. if orientation != Qt.Horizontal:
  112. return None
  113. return self.columnHeader(section)
  114. def parent(self, child):
  115. child_item = child.internalPointer()
  116. if child_item is self.root:
  117. return QModelIndex()
  118. parent_item = child_item.getParentItem()
  119. return self.createIndex(parent_item.getRow(), 0, parent_item)
  120. def index(self, row, column, parent):
  121. child_item = self.Item(parent).getChildItem(row)
  122. return self.createIndex(row, column, child_item)
  123. def DisplayData(self, item, index):
  124. return item.getData(index.column())
  125. def columnAlignment(self, column):
  126. return Qt.AlignLeft
  127. def columnFont(self, column):
  128. return None
  129. def data(self, index, role):
  130. if role == Qt.TextAlignmentRole:
  131. return self.columnAlignment(index.column())
  132. if role == Qt.FontRole:
  133. return self.columnFont(index.column())
  134. if role != Qt.DisplayRole:
  135. return None
  136. item = index.internalPointer()
  137. return self.DisplayData(item, index)
  138. # Model cache
  139. model_cache = weakref.WeakValueDictionary()
  140. model_cache_lock = threading.Lock()
  141. def LookupCreateModel(model_name, create_fn):
  142. model_cache_lock.acquire()
  143. try:
  144. model = model_cache[model_name]
  145. except:
  146. model = None
  147. if model is None:
  148. model = create_fn()
  149. model_cache[model_name] = model
  150. model_cache_lock.release()
  151. return model
  152. # Find bar
  153. class FindBar():
  154. def __init__(self, parent, finder, is_reg_expr=False):
  155. self.finder = finder
  156. self.context = []
  157. self.last_value = None
  158. self.last_pattern = None
  159. label = QLabel("Find:")
  160. label.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
  161. self.textbox = QComboBox()
  162. self.textbox.setEditable(True)
  163. self.textbox.currentIndexChanged.connect(self.ValueChanged)
  164. self.progress = QProgressBar()
  165. self.progress.setRange(0, 0)
  166. self.progress.hide()
  167. if is_reg_expr:
  168. self.pattern = QCheckBox("Regular Expression")
  169. else:
  170. self.pattern = QCheckBox("Pattern")
  171. self.pattern.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
  172. self.next_button = QToolButton()
  173. self.next_button.setIcon(parent.style().standardIcon(QStyle.SP_ArrowDown))
  174. self.next_button.released.connect(lambda: self.NextPrev(1))
  175. self.prev_button = QToolButton()
  176. self.prev_button.setIcon(parent.style().standardIcon(QStyle.SP_ArrowUp))
  177. self.prev_button.released.connect(lambda: self.NextPrev(-1))
  178. self.close_button = QToolButton()
  179. self.close_button.setIcon(parent.style().standardIcon(QStyle.SP_DockWidgetCloseButton))
  180. self.close_button.released.connect(self.Deactivate)
  181. self.hbox = QHBoxLayout()
  182. self.hbox.setContentsMargins(0, 0, 0, 0)
  183. self.hbox.addWidget(label)
  184. self.hbox.addWidget(self.textbox)
  185. self.hbox.addWidget(self.progress)
  186. self.hbox.addWidget(self.pattern)
  187. self.hbox.addWidget(self.next_button)
  188. self.hbox.addWidget(self.prev_button)
  189. self.hbox.addWidget(self.close_button)
  190. self.bar = QWidget()
  191. self.bar.setLayout(self.hbox);
  192. self.bar.hide()
  193. def Widget(self):
  194. return self.bar
  195. def Activate(self):
  196. self.bar.show()
  197. self.textbox.setFocus()
  198. def Deactivate(self):
  199. self.bar.hide()
  200. def Busy(self):
  201. self.textbox.setEnabled(False)
  202. self.pattern.hide()
  203. self.next_button.hide()
  204. self.prev_button.hide()
  205. self.progress.show()
  206. def Idle(self):
  207. self.textbox.setEnabled(True)
  208. self.progress.hide()
  209. self.pattern.show()
  210. self.next_button.show()
  211. self.prev_button.show()
  212. def Find(self, direction):
  213. value = self.textbox.currentText()
  214. pattern = self.pattern.isChecked()
  215. self.last_value = value
  216. self.last_pattern = pattern
  217. self.finder.Find(value, direction, pattern, self.context)
  218. def ValueChanged(self):
  219. value = self.textbox.currentText()
  220. pattern = self.pattern.isChecked()
  221. index = self.textbox.currentIndex()
  222. data = self.textbox.itemData(index)
  223. # Store the pattern in the combo box to keep it with the text value
  224. if data == None:
  225. self.textbox.setItemData(index, pattern)
  226. else:
  227. self.pattern.setChecked(data)
  228. self.Find(0)
  229. def NextPrev(self, direction):
  230. value = self.textbox.currentText()
  231. pattern = self.pattern.isChecked()
  232. if value != self.last_value:
  233. index = self.textbox.findText(value)
  234. # Allow for a button press before the value has been added to the combo box
  235. if index < 0:
  236. index = self.textbox.count()
  237. self.textbox.addItem(value, pattern)
  238. self.textbox.setCurrentIndex(index)
  239. return
  240. else:
  241. self.textbox.setItemData(index, pattern)
  242. elif pattern != self.last_pattern:
  243. # Keep the pattern recorded in the combo box up to date
  244. index = self.textbox.currentIndex()
  245. self.textbox.setItemData(index, pattern)
  246. self.Find(direction)
  247. def NotFound(self):
  248. QMessageBox.information(self.bar, "Find", "'" + self.textbox.currentText() + "' not found")
  249. # Context-sensitive call graph data model item base
  250. class CallGraphLevelItemBase(object):
  251. def __init__(self, glb, row, parent_item):
  252. self.glb = glb
  253. self.row = row
  254. self.parent_item = parent_item
  255. self.query_done = False;
  256. self.child_count = 0
  257. self.child_items = []
  258. def getChildItem(self, row):
  259. return self.child_items[row]
  260. def getParentItem(self):
  261. return self.parent_item
  262. def getRow(self):
  263. return self.row
  264. def childCount(self):
  265. if not self.query_done:
  266. self.Select()
  267. if not self.child_count:
  268. return -1
  269. return self.child_count
  270. def hasChildren(self):
  271. if not self.query_done:
  272. return True
  273. return self.child_count > 0
  274. def getData(self, column):
  275. return self.data[column]
  276. # Context-sensitive call graph data model level 2+ item base
  277. class CallGraphLevelTwoPlusItemBase(CallGraphLevelItemBase):
  278. def __init__(self, glb, row, comm_id, thread_id, call_path_id, time, branch_count, parent_item):
  279. super(CallGraphLevelTwoPlusItemBase, self).__init__(glb, row, parent_item)
  280. self.comm_id = comm_id
  281. self.thread_id = thread_id
  282. self.call_path_id = call_path_id
  283. self.branch_count = branch_count
  284. self.time = time
  285. def Select(self):
  286. self.query_done = True;
  287. query = QSqlQuery(self.glb.db)
  288. QueryExec(query, "SELECT call_path_id, name, short_name, COUNT(calls.id), SUM(return_time - call_time), SUM(branch_count)"
  289. " FROM calls"
  290. " INNER JOIN call_paths ON calls.call_path_id = call_paths.id"
  291. " INNER JOIN symbols ON call_paths.symbol_id = symbols.id"
  292. " INNER JOIN dsos ON symbols.dso_id = dsos.id"
  293. " WHERE parent_call_path_id = " + str(self.call_path_id) +
  294. " AND comm_id = " + str(self.comm_id) +
  295. " AND thread_id = " + str(self.thread_id) +
  296. " GROUP BY call_path_id, name, short_name"
  297. " ORDER BY call_path_id")
  298. while query.next():
  299. child_item = CallGraphLevelThreeItem(self.glb, self.child_count, self.comm_id, self.thread_id, query.value(0), query.value(1), query.value(2), query.value(3), int(query.value(4)), int(query.value(5)), self)
  300. self.child_items.append(child_item)
  301. self.child_count += 1
  302. # Context-sensitive call graph data model level three item
  303. class CallGraphLevelThreeItem(CallGraphLevelTwoPlusItemBase):
  304. def __init__(self, glb, row, comm_id, thread_id, call_path_id, name, dso, count, time, branch_count, parent_item):
  305. super(CallGraphLevelThreeItem, self).__init__(glb, row, comm_id, thread_id, call_path_id, time, branch_count, parent_item)
  306. dso = dsoname(dso)
  307. self.data = [ name, dso, str(count), str(time), PercentToOneDP(time, parent_item.time), str(branch_count), PercentToOneDP(branch_count, parent_item.branch_count) ]
  308. self.dbid = call_path_id
  309. # Context-sensitive call graph data model level two item
  310. class CallGraphLevelTwoItem(CallGraphLevelTwoPlusItemBase):
  311. def __init__(self, glb, row, comm_id, thread_id, pid, tid, parent_item):
  312. super(CallGraphLevelTwoItem, self).__init__(glb, row, comm_id, thread_id, 1, 0, 0, parent_item)
  313. self.data = [str(pid) + ":" + str(tid), "", "", "", "", "", ""]
  314. self.dbid = thread_id
  315. def Select(self):
  316. super(CallGraphLevelTwoItem, self).Select()
  317. for child_item in self.child_items:
  318. self.time += child_item.time
  319. self.branch_count += child_item.branch_count
  320. for child_item in self.child_items:
  321. child_item.data[4] = PercentToOneDP(child_item.time, self.time)
  322. child_item.data[6] = PercentToOneDP(child_item.branch_count, self.branch_count)
  323. # Context-sensitive call graph data model level one item
  324. class CallGraphLevelOneItem(CallGraphLevelItemBase):
  325. def __init__(self, glb, row, comm_id, comm, parent_item):
  326. super(CallGraphLevelOneItem, self).__init__(glb, row, parent_item)
  327. self.data = [comm, "", "", "", "", "", ""]
  328. self.dbid = comm_id
  329. def Select(self):
  330. self.query_done = True;
  331. query = QSqlQuery(self.glb.db)
  332. QueryExec(query, "SELECT thread_id, pid, tid"
  333. " FROM comm_threads"
  334. " INNER JOIN threads ON thread_id = threads.id"
  335. " WHERE comm_id = " + str(self.dbid))
  336. while query.next():
  337. child_item = CallGraphLevelTwoItem(self.glb, self.child_count, self.dbid, query.value(0), query.value(1), query.value(2), self)
  338. self.child_items.append(child_item)
  339. self.child_count += 1
  340. # Context-sensitive call graph data model root item
  341. class CallGraphRootItem(CallGraphLevelItemBase):
  342. def __init__(self, glb):
  343. super(CallGraphRootItem, self).__init__(glb, 0, None)
  344. self.dbid = 0
  345. self.query_done = True;
  346. query = QSqlQuery(glb.db)
  347. QueryExec(query, "SELECT id, comm FROM comms")
  348. while query.next():
  349. if not query.value(0):
  350. continue
  351. child_item = CallGraphLevelOneItem(glb, self.child_count, query.value(0), query.value(1), self)
  352. self.child_items.append(child_item)
  353. self.child_count += 1
  354. # Context-sensitive call graph data model
  355. class CallGraphModel(TreeModel):
  356. def __init__(self, glb, parent=None):
  357. super(CallGraphModel, self).__init__(CallGraphRootItem(glb), parent)
  358. self.glb = glb
  359. def columnCount(self, parent=None):
  360. return 7
  361. def columnHeader(self, column):
  362. headers = ["Call Path", "Object", "Count ", "Time (ns) ", "Time (%) ", "Branch Count ", "Branch Count (%) "]
  363. return headers[column]
  364. def columnAlignment(self, column):
  365. alignment = [ Qt.AlignLeft, Qt.AlignLeft, Qt.AlignRight, Qt.AlignRight, Qt.AlignRight, Qt.AlignRight, Qt.AlignRight ]
  366. return alignment[column]
  367. def FindSelect(self, value, pattern, query):
  368. if pattern:
  369. # postgresql and sqlite pattern patching differences:
  370. # postgresql LIKE is case sensitive but sqlite LIKE is not
  371. # postgresql LIKE allows % and _ to be escaped with \ but sqlite LIKE does not
  372. # postgresql supports ILIKE which is case insensitive
  373. # sqlite supports GLOB (text only) which uses * and ? and is case sensitive
  374. if not self.glb.dbref.is_sqlite3:
  375. # Escape % and _
  376. s = value.replace("%", "\%")
  377. s = s.replace("_", "\_")
  378. # Translate * and ? into SQL LIKE pattern characters % and _
  379. trans = string.maketrans("*?", "%_")
  380. match = " LIKE '" + str(s).translate(trans) + "'"
  381. else:
  382. match = " GLOB '" + str(value) + "'"
  383. else:
  384. match = " = '" + str(value) + "'"
  385. QueryExec(query, "SELECT call_path_id, comm_id, thread_id"
  386. " FROM calls"
  387. " INNER JOIN call_paths ON calls.call_path_id = call_paths.id"
  388. " INNER JOIN symbols ON call_paths.symbol_id = symbols.id"
  389. " WHERE symbols.name" + match +
  390. " GROUP BY comm_id, thread_id, call_path_id"
  391. " ORDER BY comm_id, thread_id, call_path_id")
  392. def FindPath(self, query):
  393. # Turn the query result into a list of ids that the tree view can walk
  394. # to open the tree at the right place.
  395. ids = []
  396. parent_id = query.value(0)
  397. while parent_id:
  398. ids.insert(0, parent_id)
  399. q2 = QSqlQuery(self.glb.db)
  400. QueryExec(q2, "SELECT parent_id"
  401. " FROM call_paths"
  402. " WHERE id = " + str(parent_id))
  403. if not q2.next():
  404. break
  405. parent_id = q2.value(0)
  406. # The call path root is not used
  407. if ids[0] == 1:
  408. del ids[0]
  409. ids.insert(0, query.value(2))
  410. ids.insert(0, query.value(1))
  411. return ids
  412. def Found(self, query, found):
  413. if found:
  414. return self.FindPath(query)
  415. return []
  416. def FindValue(self, value, pattern, query, last_value, last_pattern):
  417. if last_value == value and pattern == last_pattern:
  418. found = query.first()
  419. else:
  420. self.FindSelect(value, pattern, query)
  421. found = query.next()
  422. return self.Found(query, found)
  423. def FindNext(self, query):
  424. found = query.next()
  425. if not found:
  426. found = query.first()
  427. return self.Found(query, found)
  428. def FindPrev(self, query):
  429. found = query.previous()
  430. if not found:
  431. found = query.last()
  432. return self.Found(query, found)
  433. def FindThread(self, c):
  434. if c.direction == 0 or c.value != c.last_value or c.pattern != c.last_pattern:
  435. ids = self.FindValue(c.value, c.pattern, c.query, c.last_value, c.last_pattern)
  436. elif c.direction > 0:
  437. ids = self.FindNext(c.query)
  438. else:
  439. ids = self.FindPrev(c.query)
  440. return (True, ids)
  441. def Find(self, value, direction, pattern, context, callback):
  442. class Context():
  443. def __init__(self, *x):
  444. self.value, self.direction, self.pattern, self.query, self.last_value, self.last_pattern = x
  445. def Update(self, *x):
  446. self.value, self.direction, self.pattern, self.last_value, self.last_pattern = x + (self.value, self.pattern)
  447. if len(context):
  448. context[0].Update(value, direction, pattern)
  449. else:
  450. context.append(Context(value, direction, pattern, QSqlQuery(self.glb.db), None, None))
  451. # Use a thread so the UI is not blocked during the SELECT
  452. thread = Thread(self.FindThread, context[0])
  453. thread.done.connect(lambda ids, t=thread, c=callback: self.FindDone(t, c, ids), Qt.QueuedConnection)
  454. thread.start()
  455. def FindDone(self, thread, callback, ids):
  456. callback(ids)
  457. # Vertical widget layout
  458. class VBox():
  459. def __init__(self, w1, w2, w3=None):
  460. self.vbox = QWidget()
  461. self.vbox.setLayout(QVBoxLayout());
  462. self.vbox.layout().setContentsMargins(0, 0, 0, 0)
  463. self.vbox.layout().addWidget(w1)
  464. self.vbox.layout().addWidget(w2)
  465. if w3:
  466. self.vbox.layout().addWidget(w3)
  467. def Widget(self):
  468. return self.vbox
  469. # Context-sensitive call graph window
  470. class CallGraphWindow(QMdiSubWindow):
  471. def __init__(self, glb, parent=None):
  472. super(CallGraphWindow, self).__init__(parent)
  473. self.model = LookupCreateModel("Context-Sensitive Call Graph", lambda x=glb: CallGraphModel(x))
  474. self.view = QTreeView()
  475. self.view.setModel(self.model)
  476. for c, w in ((0, 250), (1, 100), (2, 60), (3, 70), (4, 70), (5, 100)):
  477. self.view.setColumnWidth(c, w)
  478. self.find_bar = FindBar(self, self)
  479. self.vbox = VBox(self.view, self.find_bar.Widget())
  480. self.setWidget(self.vbox.Widget())
  481. AddSubWindow(glb.mainwindow.mdi_area, self, "Context-Sensitive Call Graph")
  482. def DisplayFound(self, ids):
  483. if not len(ids):
  484. return False
  485. parent = QModelIndex()
  486. for dbid in ids:
  487. found = False
  488. n = self.model.rowCount(parent)
  489. for row in xrange(n):
  490. child = self.model.index(row, 0, parent)
  491. if child.internalPointer().dbid == dbid:
  492. found = True
  493. self.view.setCurrentIndex(child)
  494. parent = child
  495. break
  496. if not found:
  497. break
  498. return found
  499. def Find(self, value, direction, pattern, context):
  500. self.view.setFocus()
  501. self.find_bar.Busy()
  502. self.model.Find(value, direction, pattern, context, self.FindDone)
  503. def FindDone(self, ids):
  504. found = True
  505. if not self.DisplayFound(ids):
  506. found = False
  507. self.find_bar.Idle()
  508. if not found:
  509. self.find_bar.NotFound()
  510. # Action Definition
  511. def CreateAction(label, tip, callback, parent=None, shortcut=None):
  512. action = QAction(label, parent)
  513. if shortcut != None:
  514. action.setShortcuts(shortcut)
  515. action.setStatusTip(tip)
  516. action.triggered.connect(callback)
  517. return action
  518. # Typical application actions
  519. def CreateExitAction(app, parent=None):
  520. return CreateAction("&Quit", "Exit the application", app.closeAllWindows, parent, QKeySequence.Quit)
  521. # Typical MDI actions
  522. def CreateCloseActiveWindowAction(mdi_area):
  523. return CreateAction("Cl&ose", "Close the active window", mdi_area.closeActiveSubWindow, mdi_area)
  524. def CreateCloseAllWindowsAction(mdi_area):
  525. return CreateAction("Close &All", "Close all the windows", mdi_area.closeAllSubWindows, mdi_area)
  526. def CreateTileWindowsAction(mdi_area):
  527. return CreateAction("&Tile", "Tile the windows", mdi_area.tileSubWindows, mdi_area)
  528. def CreateCascadeWindowsAction(mdi_area):
  529. return CreateAction("&Cascade", "Cascade the windows", mdi_area.cascadeSubWindows, mdi_area)
  530. def CreateNextWindowAction(mdi_area):
  531. return CreateAction("Ne&xt", "Move the focus to the next window", mdi_area.activateNextSubWindow, mdi_area, QKeySequence.NextChild)
  532. def CreatePreviousWindowAction(mdi_area):
  533. return CreateAction("Pre&vious", "Move the focus to the previous window", mdi_area.activatePreviousSubWindow, mdi_area, QKeySequence.PreviousChild)
  534. # Typical MDI window menu
  535. class WindowMenu():
  536. def __init__(self, mdi_area, menu):
  537. self.mdi_area = mdi_area
  538. self.window_menu = menu.addMenu("&Windows")
  539. self.close_active_window = CreateCloseActiveWindowAction(mdi_area)
  540. self.close_all_windows = CreateCloseAllWindowsAction(mdi_area)
  541. self.tile_windows = CreateTileWindowsAction(mdi_area)
  542. self.cascade_windows = CreateCascadeWindowsAction(mdi_area)
  543. self.next_window = CreateNextWindowAction(mdi_area)
  544. self.previous_window = CreatePreviousWindowAction(mdi_area)
  545. self.window_menu.aboutToShow.connect(self.Update)
  546. def Update(self):
  547. self.window_menu.clear()
  548. sub_window_count = len(self.mdi_area.subWindowList())
  549. have_sub_windows = sub_window_count != 0
  550. self.close_active_window.setEnabled(have_sub_windows)
  551. self.close_all_windows.setEnabled(have_sub_windows)
  552. self.tile_windows.setEnabled(have_sub_windows)
  553. self.cascade_windows.setEnabled(have_sub_windows)
  554. self.next_window.setEnabled(have_sub_windows)
  555. self.previous_window.setEnabled(have_sub_windows)
  556. self.window_menu.addAction(self.close_active_window)
  557. self.window_menu.addAction(self.close_all_windows)
  558. self.window_menu.addSeparator()
  559. self.window_menu.addAction(self.tile_windows)
  560. self.window_menu.addAction(self.cascade_windows)
  561. self.window_menu.addSeparator()
  562. self.window_menu.addAction(self.next_window)
  563. self.window_menu.addAction(self.previous_window)
  564. if sub_window_count == 0:
  565. return
  566. self.window_menu.addSeparator()
  567. nr = 1
  568. for sub_window in self.mdi_area.subWindowList():
  569. label = str(nr) + " " + sub_window.name
  570. if nr < 10:
  571. label = "&" + label
  572. action = self.window_menu.addAction(label)
  573. action.setCheckable(True)
  574. action.setChecked(sub_window == self.mdi_area.activeSubWindow())
  575. action.triggered.connect(lambda x=nr: self.setActiveSubWindow(x))
  576. self.window_menu.addAction(action)
  577. nr += 1
  578. def setActiveSubWindow(self, nr):
  579. self.mdi_area.setActiveSubWindow(self.mdi_area.subWindowList()[nr - 1])
  580. # Font resize
  581. def ResizeFont(widget, diff):
  582. font = widget.font()
  583. sz = font.pointSize()
  584. font.setPointSize(sz + diff)
  585. widget.setFont(font)
  586. def ShrinkFont(widget):
  587. ResizeFont(widget, -1)
  588. def EnlargeFont(widget):
  589. ResizeFont(widget, 1)
  590. # Unique name for sub-windows
  591. def NumberedWindowName(name, nr):
  592. if nr > 1:
  593. name += " <" + str(nr) + ">"
  594. return name
  595. def UniqueSubWindowName(mdi_area, name):
  596. nr = 1
  597. while True:
  598. unique_name = NumberedWindowName(name, nr)
  599. ok = True
  600. for sub_window in mdi_area.subWindowList():
  601. if sub_window.name == unique_name:
  602. ok = False
  603. break
  604. if ok:
  605. return unique_name
  606. nr += 1
  607. # Add a sub-window
  608. def AddSubWindow(mdi_area, sub_window, name):
  609. unique_name = UniqueSubWindowName(mdi_area, name)
  610. sub_window.setMinimumSize(200, 100)
  611. sub_window.resize(800, 600)
  612. sub_window.setWindowTitle(unique_name)
  613. sub_window.setAttribute(Qt.WA_DeleteOnClose)
  614. sub_window.setWindowIcon(sub_window.style().standardIcon(QStyle.SP_FileIcon))
  615. sub_window.name = unique_name
  616. mdi_area.addSubWindow(sub_window)
  617. sub_window.show()
  618. # Main window
  619. class MainWindow(QMainWindow):
  620. def __init__(self, glb, parent=None):
  621. super(MainWindow, self).__init__(parent)
  622. self.glb = glb
  623. self.setWindowTitle("Exported SQL Viewer: " + glb.dbname)
  624. self.setWindowIcon(self.style().standardIcon(QStyle.SP_ComputerIcon))
  625. self.setMinimumSize(200, 100)
  626. self.mdi_area = QMdiArea()
  627. self.mdi_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
  628. self.mdi_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
  629. self.setCentralWidget(self.mdi_area)
  630. menu = self.menuBar()
  631. file_menu = menu.addMenu("&File")
  632. file_menu.addAction(CreateExitAction(glb.app, self))
  633. edit_menu = menu.addMenu("&Edit")
  634. edit_menu.addAction(CreateAction("&Find...", "Find items", self.Find, self, QKeySequence.Find))
  635. edit_menu.addAction(CreateAction("&Shrink Font", "Make text smaller", self.ShrinkFont, self, [QKeySequence("Ctrl+-")]))
  636. edit_menu.addAction(CreateAction("&Enlarge Font", "Make text bigger", self.EnlargeFont, self, [QKeySequence("Ctrl++")]))
  637. reports_menu = menu.addMenu("&Reports")
  638. reports_menu.addAction(CreateAction("Context-Sensitive Call &Graph", "Create a new window containing a context-sensitive call graph", self.NewCallGraph, self))
  639. self.window_menu = WindowMenu(self.mdi_area, menu)
  640. def Find(self):
  641. win = self.mdi_area.activeSubWindow()
  642. if win:
  643. try:
  644. win.find_bar.Activate()
  645. except:
  646. pass
  647. def ShrinkFont(self):
  648. win = self.mdi_area.activeSubWindow()
  649. ShrinkFont(win.view)
  650. def EnlargeFont(self):
  651. win = self.mdi_area.activeSubWindow()
  652. EnlargeFont(win.view)
  653. def NewCallGraph(self):
  654. CallGraphWindow(self.glb, self)
  655. # Global data
  656. class Glb():
  657. def __init__(self, dbref, db, dbname):
  658. self.dbref = dbref
  659. self.db = db
  660. self.dbname = dbname
  661. self.app = None
  662. self.mainwindow = None
  663. # Database reference
  664. class DBRef():
  665. def __init__(self, is_sqlite3, dbname):
  666. self.is_sqlite3 = is_sqlite3
  667. self.dbname = dbname
  668. def Open(self, connection_name):
  669. dbname = self.dbname
  670. if self.is_sqlite3:
  671. db = QSqlDatabase.addDatabase("QSQLITE", connection_name)
  672. else:
  673. db = QSqlDatabase.addDatabase("QPSQL", connection_name)
  674. opts = dbname.split()
  675. for opt in opts:
  676. if "=" in opt:
  677. opt = opt.split("=")
  678. if opt[0] == "hostname":
  679. db.setHostName(opt[1])
  680. elif opt[0] == "port":
  681. db.setPort(int(opt[1]))
  682. elif opt[0] == "username":
  683. db.setUserName(opt[1])
  684. elif opt[0] == "password":
  685. db.setPassword(opt[1])
  686. elif opt[0] == "dbname":
  687. dbname = opt[1]
  688. else:
  689. dbname = opt
  690. db.setDatabaseName(dbname)
  691. if not db.open():
  692. raise Exception("Failed to open database " + dbname + " error: " + db.lastError().text())
  693. return db, dbname
  694. # Main
  695. def Main():
  696. if (len(sys.argv) < 2):
  697. print >> sys.stderr, "Usage is: exported-sql-viewer.py <database name>"
  698. raise Exception("Too few arguments")
  699. dbname = sys.argv[1]
  700. is_sqlite3 = False
  701. try:
  702. f = open(dbname)
  703. if f.read(15) == "SQLite format 3":
  704. is_sqlite3 = True
  705. f.close()
  706. except:
  707. pass
  708. dbref = DBRef(is_sqlite3, dbname)
  709. db, dbname = dbref.Open("main")
  710. glb = Glb(dbref, db, dbname)
  711. app = QApplication(sys.argv)
  712. glb.app = app
  713. mainwindow = MainWindow(glb)
  714. glb.mainwindow = mainwindow
  715. mainwindow.show()
  716. err = app.exec_()
  717. db.close()
  718. sys.exit(err)
  719. if __name__ == "__main__":
  720. Main()