Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

""" Displays a graph-based representation of the Ontology and allows the 

Ontology to be modified graphically. 

 

This module contains: 

 

GraphWidget: Displays and allows modification of a graph of the Ontology. 

 

""" 

 

from PySide.QtCore import QLineF, Slot, Qt 

from PySide.QtGui import QColor, QPen, QMenu, QInputDialog, QMessageBox, QCompleter, QFontMetricsF 

from PySide.QtGui import QGraphicsEllipseItem, QGraphicsSimpleTextItem, QGraphicsScene, QGraphicsItem 

from PySide.QtGui import QPrintPreviewDialog, QPainter, QApplication 

import pygraphviz 

import random 

import logging 

 

 

from pySUMOQt.Designer.GraphWidget import Ui_Form 

from pySUMOQt.Widget.Widget import RWWidget 

import weakref 

from pysumo.syntaxcontroller import Ontology 

 

def insert_newlines(string, every=64): 

    """ Insert a newline after ’every‘ characters 

     

        Arguments: 

         

            - every : The amount of characters before a newline is inserted  

             

    """ 

    return '\n'.join(string[i:i + every] for i in range(0, len(string), every)) 

 

 

class QtNode(QGraphicsEllipseItem): 

    """ A Node representation in Qt""" 

    callback = None 

    def setCallback(self, f): 

        """ Sets a callback function to call after the position has changed""" 

        self.callback = f 

 

    def setNode(self, node): 

        """ Save the graphviz node""" 

        self.node = node 

 

    def itemChange(self, itemChange, val): 

        """ Override Qt 

         

        Renew the arrows 

        """ 

        if (itemChange == QGraphicsItem.ItemPositionHasChanged): 

            if self.callback is not None: 

                self.callback().renewplot() 

        return super().itemChange(itemChange, val) 

 

    def mouseDoubleClickEvent(self, event): 

        """ Override Qt 

         

        Add a relation or save start relation point when double clicking 

        """ 

        if self.callback is not None: 

            self.callback().addRelation(self) 

 

class GraphWidget(RWWidget, Ui_Form): 

 

    """ Displays a graph of the Ontology and passes all modifications to the 

    SyntaxController. 

 

    Variables: 

 

    - abstractGraph: The currently displayed AbstractGraph. 

    - gv: The layouted version of the current DotGraph. 

 

    """ 

 

    def __init__(self, mainwindow): 

        """ Initializes the GraphWidget. """ 

        super(GraphWidget, self).__init__(mainwindow) 

        self.setupUi(self.mw) 

        self.startRelation = None 

        self.abstractGraph = None 

        self.gv = pygraphviz.AGraph(strict = False) 

        self.widget = self.layoutWidget 

        self.log = logging.getLogger('.' + __name__) 

        self.nodesToQNodes = {} 

        self.qLines = [] 

        self.qpens = {} 

        self.completer = QCompleter(list("")) 

        self.completer.setCaseSensitivity(Qt.CaseInsensitive) 

        self.completer.setWidget(self.lineEdit) 

 

        self.lastScale = 1 

        self.initMenu() 

        self.roots = set() 

        self.doubleSpinBox.valueChanged[float].connect(self.changeScale) 

        self.lineEdit.textChanged.connect(self.searchNode) 

        self.rootSelector.insertItem(0, "---") 

        self.rootSelector.currentIndexChanged[str].connect(self.newRoot) 

        self.relations.currentIndexChanged[str].connect(self.newVariant) 

        self.depth.valueChanged.connect(self.newRoot) 

        self._updateActiveOntology() 

        self.graphicsView.setScene(QGraphicsScene()) 

#     def initRelationBox(self): 

#         m = self.relations.model() 

#         for i in self.getIndexAbstractor().get_graph('instance').relations.keys(): 

#             m.appendRow(QStandardItem(i)) 

 

    def refresh(self): 

        """ Override Widget 

        Updates the GraphWidget regarding to latest indexabstractor changes 

        """ 

        self.newVariant() 

        super(GraphWidget, self).refresh() 

 

    def getActiveOntology(self): 

        idx = self.activeOntology.currentIndex() 

        return self.activeOntology.itemData(idx) 

 

    def _updateActiveOntology(self): 

        currentText = self.activeOntology.currentText() 

        self.activeOntology.clear() 

        idx = -1 

        count = 0 

        for i in self.getIndexAbstractor().ontologies : 

            if currentText == i.name : 

                idx = count 

            self.activeOntology.addItem(i.name, i) 

            count = count + 1 

        self.activeOntology.setCurrentIndex(idx) 

 

    def searchNode(self, search): 

        """Search the node and focus the GraphicView to the node """ 

        try: 

            #self.completer.setCompletionPrefix(search) 

            #self.completer.complete() 

            node = self.nodesToQNodes[search] 

            self.graphicsView.centerOn(node) 

        except KeyError: 

            pass # TODO: Mach hier einen Log 

 

    def addRelation(self, qnode): 

        """ Adds a relation or save a starting point 

         

        """ 

        if self.startRelation != None: # yeah a new relation 

            self.log.info("Add relation from " + self.startRelation.node + " to " + qnode.node ) 

            if self.relations.currentText() == "---": 

                msg = QMessageBox() 

                msg.setText("Please choose a valid variant.") 

                msg.exec_() 

                return 

            addstr = "\n(" + self.relations.currentText() + " " + self.startRelation.node + " " + qnode.node + ")\n" 

            self.startRelation = None 

            ontology = None 

            for i in self.getIndexAbstractor().ontologies: 

                if i.name == self.activeOntology.currentText(): 

                    ontology = i 

 

            if ontology is None: 

                msg = QMessageBox() 

                msg.setText("Please choose a valid Ontology to write to.") 

                msg.exec_() 

                return 

            self.lineEdit.setText(qnode.node) 

            x = self.getIndexAbstractor().get_ontology_file(ontology) 

            x.seek(0, 2) 

            x.write(addstr) 

            QApplication.setOverrideCursor(Qt.BusyCursor) 

            self.SyntaxController.add_ontology(ontology, newversion=x.getvalue()) 

            QApplication.setOverrideCursor(Qt.ArrowCursor) 

            self.commit() 

        else: 

            self.log.info("Starting node is " + qnode.node) 

            self.startRelation = qnode 

 

    def _printPreview_(self): 

        dialog = QPrintPreviewDialog() 

        dialog.paintRequested.connect(self.print_) 

        dialog.exec_() 

 

    def print_(self, printer): 

        painter = QPainter(printer) 

        painter.setRenderHint(QPainter.Antialiasing) 

        self.graphicsView.render(painter) 

 

    def _zoomIn_(self): 

        val = self.doubleSpinBox.value() + 0.10 

        self.doubleSpinBox.setValue(val) 

 

    def _zoomOut_(self): 

        val = self.doubleSpinBox.value() - 0.10 

        self.doubleSpinBox.setValue(val) 

 

    @Slot(float) 

    def changeScale(self, val): 

        """ Scale the GraphicView to val 

         

        Arguments: 

         

            - val: The value to scale to. In Designer: 0.01 <= val <= 5 

         

        """ 

        toScale = val / self.lastScale 

        self.lastScale = val 

        self.graphicsView.scale(toScale, toScale) 

 

    @Slot() 

    def renewplot(self): 

        """ Do not layout anything, but redraw all lines""" 

        scene = self.graphicsView.scene() 

        self.roots = set() 

        # scene.changed.disconnect(self.renewplot) 

        for i in self.qLines: 

            scene.removeItem(i) 

 

        self.qLines = [] 

 

        for edge in self.gv.edges_iter(): 

 

            qnode1 = self.nodesToQNodes[edge[0]] 

            qnode2 = self.nodesToQNodes[edge[1]] 

            line = QLineF(qnode1.pos(), qnode2.pos()) 

            line.setLength(line.length() - 40) 

            end = line.p2() 

 

            arrowLine1 = QLineF() 

            arrowLine1.setP1(end) 

            arrowLine1.setLength(10) 

            arrowLine1.setAngle(line.angle() + 210) 

 

            arrowLine2 = QLineF() 

            arrowLine2.setP1(end) 

            arrowLine2.setLength(10) 

            arrowLine2.setAngle(line.angle() - 210) 

            if edge.attr['color'] not in self.qpens: 

                self.qpens[edge.attr['color']] = QPen( 

                    QColor(edge.attr['color'])) 

 

            item = scene.addLine(line, self.qpens[edge.attr['color']]) 

            item.setZValue(-1) 

            item.setFlag(QGraphicsItem.ItemIsSelectable, True) 

            self.qLines.append(item) 

            item = scene.addLine(arrowLine1, self.qpens[edge.attr['color']]) 

            self.qLines.append(item) 

            item = scene.addLine(arrowLine2, self.qpens[edge.attr['color']]) 

            self.qLines.append(item) 

 

            self.roots.add(edge[0]) 

        # scene.changed.connect(self.renewplot) 

 

    def plot(self): 

        """ 

        Creates a QGraphicScene for the layouted graph in self.gv 

        This function has to be called every time, a node change happened. 

        """ 

        scene = self.graphicsView.scene() 

        scene.clear() 

        self.nodesToQNodes = {} 

        self.qLines = [] 

        for node in self.gv.nodes_iter(): 

            (x, y) = node.attr['pos'].split(',') 

            x = float(x) 

            y = float(y) 

            point = self.graphicsView.mapToScene(int(x),int(y)) 

            qnode = self.createQtNode(node, point.x(), point.y()) 

            scene.addItem(qnode) 

 

            self.nodesToQNodes[node] = qnode 

 

 

 

        self.completer = QCompleter(list(self.nodesToQNodes.keys())) 

        self.completer.setCaseSensitivity(Qt.CaseInsensitive) 

        self.completer.setWidget(self.lineEdit) 

        self.lineEdit.setCompleter(self.completer) 

        self.renewplot() 

        self.searchNode(self.lineEdit.text()) 

    def createQtNode(self, node, posx, posy, color = QColor(255,150,150)): 

        """ Create a QtNode with given position, color for given node 

         

        Arguments: 

             

            - node: The graphviz node 

            - posx: The x position from graphviz layout 

            - posy: The y position from graphviz layout 

            - color: The color of circle (red by default) 

         

        """ 

        #dpi = float(self.gv.graph_attr['dpi']) 

        dpi = 96 

        try: 

            width = float(node.attr['width']) 

            height = float(node.attr['height']) 

        except ValueError: 

            #New created node 

            width = 300 / 96 

            height = 40 / 96 

 

        qnode = QtNode(-width * dpi / 2, -height * dpi / 2, width* dpi,  height * dpi) 

        qnode.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) 

        qnode.setPos(posx, posy) 

        qnode.setFlag(QGraphicsItem.ItemIsMovable) 

        qnode.setCallback(weakref.ref(self)) 

        qnode.setNode(node) 

        qnode.setBrush(color) 

        txt = QGraphicsSimpleTextItem(qnode) 

        font = txt.font() 

        font.setPointSize(14) 

        txt.setFont(font) 

        txt.setText(node) 

        txtwidth = QFontMetricsF(font).width(node) 

        txtheight = QFontMetricsF(font).height() 

        toLeft = (-width * dpi/ 2) + (width * dpi - txtwidth) / 2 

        toBottom = (-height * dpi/ 2) + (height * dpi - txtheight) / 2 

        txt.setPos(toLeft, toBottom) 

 

 

 

        return qnode 

 

    def initMenu(self): 

        """ 

        Configure the Widget to provide a handmade CustomContextMenu  

        """ 

        self.graphicsView.setContextMenuPolicy(Qt.CustomContextMenu) 

        self.graphicsView.customContextMenuRequested.connect(self.showContextMenu) 

 

    def showContextMenu(self, pos): 

        """ 

        Shows a context menu to add a node in the graph widget 

        """ 

        gpos = self.graphicsView.mapToGlobal(pos) 

        menu = QMenu() 

        actionAddNode = menu.addAction("Add Node") 

        QAction = menu.exec_(gpos) 

 

        if (actionAddNode == QAction): 

            (text, ok) = QInputDialog.getText(self.graphicsView, "Insert Node Name", "Please insert a name for the node") 

            if ok: 

                if text not in self.nodesToQNodes: 

                    #User clicked on ok. Otherwise do nothing 

                    self.gv.add_node(text) 

                    node = self.gv.get_node(text) 

                    qnode = self.createQtNode(node, 0, 0, QColor(204, 255, 255)) 

 

                    self.graphicsView.scene().addItem(qnode) 

                    qnode.setPos(self.graphicsView.mapToScene(gpos)) 

                    qnode.setPos(qnode.x(), qnode.y() - 200) 

                    self.nodesToQNodes[node] = qnode 

                else: 

                    msg = QMessageBox() 

                    msg.setText("The node already exists.") 

                    msg.exec_() 

                self.searchNode(text) 

    @Slot() 

    def newRoot(self): 

        """ Change to new root set in the widget and redraw""" 

        root = self.rootSelector.currentText() 

        variant = [(0, self.relations.currentText())] 

        if root == "---": 

            root = None 

 

        depth = None 

        if self.depth.value() != -1: 

            depth = self.depth.value() 

        if variant == "---": 

            variant = '' 

 

        self.createGV(variant, root, depth) 

        self.plot() 

        self.searchNode(root) 

 

    def newVariant(self): 

        """ Change to new variant set in the widget and redraw""" 

        self.rootSelector.currentIndexChanged[str].disconnect(self.newRoot) 

        self.rootSelector.clear() 

        self.rootSelector.insertItem(0, "---") 

        self.newRoot() 

        self.rootSelector.insertItems(1, list(self.roots)) 

        self.rootSelector.currentIndexChanged[str].connect(self.newRoot) 

 

    def createGV(self, variant='instance', r=None, d=None): 

        """ Create a pygraphviz graph from pysumo abstract graph and layout it. 

         

        Arguments:  

             

            - variant: The variant to use (e.g. instance) 

            - r: The root 

            - d: The depth (none for infinite depth 

         

        """ 

        gv = pygraphviz.AGraph(strict=False,overlap="scale") 

        y = self.getIndexAbstractor().get_graph(variant, root=r, depth=d) 

        if y is None or len(y.relations) == 0: 

            return 

        QApplication.setOverrideCursor(Qt.BusyCursor) 

        colors = ["black", "red", "blue", "green", "darkorchid", "gold2", 

                  "yellow", "turquoise", "sienna", "darkgreen"] 

        for k in y.relations.keys(): 

            l = [(k, v) for v in y.relations[k]] 

            gv.add_edges_from(l, color=random.choice(colors)) 

 

        gv.layout("sfdp") 

 

        self.gv = gv 

        QApplication.setOverrideCursor(Qt.ArrowCursor)