forked from BhallaLab/moose-gui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjectedit.py
495 lines (443 loc) · 18.2 KB
/
objectedit.py
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# objectedit.py ---
#
# Filename: objectedit.py
# Description:
# Author: Subhasis Ray
# Maintainer:
# Created: Wed Jun 30 11:18:34 2010 (+0530)
# Version:
# Last-Updated: Wed Mar 28 14:26:59 2014 (+0530)
# By: Harsha
# Update #: 917
# URL:
# Keywords:
# Compatibility:
#
#
# Commentary:
#
# This code is for a widget to edit MOOSE objects. We can now track if
# a field is a Value field and make it editable accordingly. There
# seems to be no clean way of determining whether the field is worth
# plotting (without a knowledge of the model/biology there is no way
# we can tell this). But we can of course check if the field is a
# numeric one.
#
#
# Change log:
#
# Wed Jun 30 11:18:34 2010 (+0530) - Originally created by Subhasis
# Ray, the model and the view
#
# Modified/adapted to dh_branch by Chaitanya/Harsharani
#
# Thu Apr 18 18:37:31 IST 2013 - Reintroduced into multiscale GUI by
# Subhasis
#
# Fri Apr 19 15:05:53 IST 2013 - Subhasis added undo redo
# feature. Create ObjectEditModel as part of ObjectEditView.
#
#
# This program 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, or
# (at your option) any later version.
#
# This program 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 this program; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth
# Floor, Boston, MA 02110-1301, USA.
#
#
# Code:
import PyQt4
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtGui import QTextEdit
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QGridLayout
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QSizePolicy
from PyQt4.QtCore import QMargins
from PyQt4.QtGui import QSplitter
import sys
from collections import deque
import traceback
sys.path.append('../python')
import moose
import defaults
import config
from plugins.kkitUtil import getColor
#these fields will be ignored
extra_fields = ['this',
'me',
'parent',
'path',
'children',
'linearSize',
'objectDimensions',
'lastDimension',
'localNumField',
'pathIndices',
'msgOut',
'msgIn',
'diffConst',
'speciesId',
'Coordinates',
'neighbors',
'DiffusionArea',
'DiffusionScaling',
'x',
'x0',
'x1',
'dx',
'nx',
'y',
'y0',
'y1',
'dy',
'ny',
'z',
'z0',
'z1',
'dz',
'nz',
'coords',
'isToroid',
'preserveNumEntries',
# 'numKm',
'numSubstrates',
'concK1',
'meshToSpace',
'spaceToMesh',
'surface',
'method',
'alwaysDiffuse',
'numData',
'numField',
'valueFields',
'sourceFields',
'motorConst',
'destFields',
'dt',
'tick',
'idValue',
'index',
'fieldIndex'
]
class ObjectEditModel(QtCore.QAbstractTableModel):
"""Model class for editing MOOSE elements. This is not to be used
directly, except that its undo and redo slots should be connected
to by the GUI actions for the same.
SIGNALS:
objectNameChanged(PyQt_PyObject): when a moose object's name is
changed, this signal is emitted with the object as argument. This
can be captured by widgets that display the object name.
dataChanged: emitted when any data is changed in the moose object
"""
objectNameChanged = QtCore.pyqtSignal('PyQt_PyObject')
# dataChanged = QtCore.pyqtSignal('PyQt_PyObject')
def __init__(self, datain, headerdata=['Field','Value'], undolen=100, parent=None, *args):
QtCore.QAbstractTableModel.__init__(self, parent, *args)
self.fieldFlags = {}
self.fields = []
self.mooseObject = datain
self.headerdata = headerdata
self.undoStack = deque(maxlen=undolen)
self.redoStack = deque(maxlen=undolen)
self.checkState_ = False
for fieldName in self.mooseObject.getFieldNames('valueFinfo'):
if fieldName in extra_fields :
continue
value = self.mooseObject.getField(fieldName)
self.fields.append(fieldName)
#harsha: For signalling models will be pulling out notes field from Annotator
# can updates if exist for other types also
if ( isinstance(self.mooseObject, moose.PoolBase)
#or isinstance(self.mooseObject,moose.ReacBase)
or isinstance(self.mooseObject,moose.EnzBase) ) :
self.fields.append("Color")
# self.fields.append("Notes")
flag = QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable
self.fieldFlags[fieldName] = flag
def rowCount(self, parent):
return len(self.fields)
def columnCount(self, parent):
return len(self.headerdata)
def setData(self, index, value, role=QtCore.Qt.EditRole):
if not index.isValid() or index.row () >= len(self.fields) or index.column() != 1:
return False
print(value)
field = self.fields[index.row()]
if (role == QtCore.Qt.CheckStateRole):
if (index.column() == 1):
self.checkState_ = value
return True
else:
value = str(value.toString()).strip() # convert Qt datastructure to Python string
if len(value) == 0:
return False
if field == "Notes":
field = "notes"
ann = moose.Annotator(self.mooseObject.path+'/info')
oldValue = ann.getField(field)
value = type(oldValue)(value)
ann.setField(field,value)
self.undoStack.append((index,oldValue))
else:
oldValue = self.mooseObject.getField(field)
value = type(oldValue)(value)
self.mooseObject.setField(field, value)
self.undoStack.append((index, oldValue))
if field == 'name':
self.emit(QtCore.SIGNAL('objectNameChanged(PyQt_PyObject)'), self.mooseObject)
return True
self.dataChanged.emit(index, index)
return True
def undo(self):
print 'Undo'
if len(self.undoStack) == 0:
raise Info('No more undo information')
index, oldvalue, = self.undoStack.pop()
field = self.fields[index.row()]
currentvalue = self.mooseObject.getField(field)
oldvalue = type(currentvalue)(oldvalue)
self.redoStack.append((index, str(currentvalue)))
self.mooseObject.setField(field, oldvalue)
if field == 'name':
self.objectNameChanged.emit(self.mooseObject)
self.emit(QtCore.SIGNAL('dataChanged(const QModelIndex&, const QModelIndex&)'), index, index)
def redo(self):
if len(self.redoStack) ==0:
raise Info('No more redo information')
index, oldvalue, = self.redoStack.pop()
currentvalue = self.mooseObject.getField(self.fields[index.row()])
self.undoStack.append((index, str(currentvalue)))
self.mooseObject.setField(self.fields[index.row()], type(currentvalue)(oldvalue))
if field == 'name':
self.emit(QtCore.SIGNAL('objectNameChanged(PyQt_PyObject)'), self.mooseObject)
self.emit(QtCore.SIGNAL('dataChanged(const QModelIndex&, const QModelIndex&)'), index, index)
def flags(self, index):
flag = QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
#flag = QtCore.Qt.NoItemFlags
if not index.isValid():
return None
# Replacing the `outrageous` up stuff with something sensible
field = self.fields[index.row()]
newstr = field[0]
newstr = newstr.upper()
field_string = newstr + field[1:]
setter = 'set%s' %(field_string)
#setter = 'set_%s' % (self.fields[index.row()])
#print " from Object setter",setter, "object",self.mooseObject, " ",self.mooseObject.getFieldNames('destFinfo');
if index.column() == 1:
# if field == "Color":
# flag = QtCore.Qt.ItemIsEnabled
if field == "Notes":
ann = moose.Annotator(self.mooseObject.path+'/info')
if setter in ann.getFieldNames('destFinfo'):
flag |= QtCore.Qt.ItemIsEditable
if isinstance(self.mooseObject, moose.PoolBase) or isinstance(self.mooseObject,moose.Function):
if field == 'volume':# or field == 'expr':
pass
elif setter in self.mooseObject.getFieldNames('destFinfo'):
flag |= QtCore.Qt.ItemIsEditable
else:
if setter in self.mooseObject.getFieldNames('destFinfo'):
flag |= QtCore.Qt.ItemIsEditable
#if field == "Notes":
# flag |= QtCore.Qt.ItemIsEditable
# !! Replaced till here
return flag
def data(self, index, role):
ret = None
field = self.fields[index.row()]
if index.column() == 0 and role == QtCore.Qt.DisplayRole:
try:
ret = QtCore.QVariant(QtCore.QString(field)+' ('+defaults.FIELD_UNITS[field]+')')
except KeyError:
ret = QtCore.QVariant(QtCore.QString(field))
elif index.column() == 1:
if role==QtCore.Qt.CheckStateRole:
if ((str(field) == "plot Conc") or (str(field) == "plot n") ):
# print index.data(QtCore.Qt. ), str(field)
return self.checkState_
elif (role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole):
try:
if (str(field) =="Color" ):
return QtGui.QPushButton("Press Me!")
if ( (str(field) != "Notes") and (str(field) != "className")):
ret = self.mooseObject.getField(str(field))
ret = QtCore.QVariant(QtCore.QString(str(ret)))
elif(str(field) == "className"):
ret = self.mooseObject.getField(str(field))
if 'Zombie' in ret:
ret = ret.split('Zombie')[1]
ret = QtCore.QVariant(QtCore.QString(str(ret)))
elif(str(field) == "Notes"):
astr = self.mooseObject.path+'/info'
mastr = moose.Annotator(astr)
ret = (mastr).getField(str('notes'))
ret = QtCore.QVariant(QtCore.QString(str(ret)))
except ValueError:
ret = None
return ret
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return QtCore.QVariant(self.headerdata[col])
return QtCore.QVariant()
class ObjectEditView(QtGui.QTableView):
"""View class for object editor.
This class creates an instance of ObjectEditModel using the moose
element passed as its first argument.
undolen - specifies the size of the undo stack. By default set to
OBJECT_EDIT_UNDO_LENGTH constant in defaults.py. Specify something smaller if
large number of objects are likely to be edited.
To enable undo/redo conect the corresponding actions from the gui
to view.model().undo and view.model().redo slots.
"""
def __init__(self, mobject, undolen=defaults.OBJECT_EDIT_UNDO_LENGTH, parent=None):
QtGui.QTableView.__init__(self, parent)
#self.setEditTriggers(self.DoubleClicked | self.SelectedClicked | self.EditKeyPressed)
vh = self.verticalHeader()
vh.setVisible(False)
hh = self.horizontalHeader()
hh.setStretchLastSection(True)
self.setAlternatingRowColors(True)
self.resizeColumnsToContents()
self.setModel(ObjectEditModel(mobject, undolen=undolen))
self.colorButton = QtGui.QPushButton()
self.colorDialog = QtGui.QColorDialog()
self.textEdit = QTextEdit()
try:
notesIndex = self.model().fields.index("Notes")
self.setIndexWidget(self.model().index(notesIndex,1), self.textEdit)
info = moose.Annotator(self.model().mooseObject.path+'/info')
self.textEdit.setText(QtCore.QString(info.getField('notes')))
self.setRowHeight(notesIndex, self.rowHeight(notesIndex) * 3)
# self.colorDialog.colorSelected.connect(
# lambda color:
#
# self.setColor(getColor(self.model().mooseObject.path+'/info')[1])
except:
pass
try:
colorIndex = self.model().fields.index("Color")
self.colorButton.clicked.connect(self.colorDialog.show)
self.colorButton.setFocusPolicy(PyQt4.QtCore.Qt.NoFocus)
self.colorDialog.colorSelected.connect(
lambda color: self.colorButton.setStyleSheet(
"QPushButton {"
+ "background-color: {0}; color: {0};".format(color.name())
+ "}"
)
)
self.setIndexWidget(self.model().index(colorIndex,1), self.colorButton)
# self.colorDialog.colorSelected.connect(
# lambda color:
#
self.setColor(getColor(self.model().mooseObject.path+'/info')[1])
except:
pass
print 'Created view with', mobject
def setColor(self, color):
self.colorButton.setStyleSheet(
"QPushButton {"
+ "background-color: {0}; color: {0};".format(color.name())
+ "}"
)
self.colorDialog.setCurrentColor(color)
def dataChanged(self, tl, br):
QtGui.QTableView.dataChanged(self, tl, br)
self.viewport().update()
class ObjectEditDockWidget(QtGui.QDockWidget):
"""A dock widget whose title is set by the current moose
object. Allows switching the moose object. It stores the created
view in a dict for future use.
TODO possible performance issue: storing the views (along with
their models) ensures the undo history for each object is
retained. But without a limit on the number of views stored, it
will be wasteful on memory.
"""
objectNameChanged = QtCore.pyqtSignal('PyQt_PyObject')
colorChanged = QtCore.pyqtSignal(object, object)
def __init__(self, mobj='/', parent=None, flags=None):
QtGui.QDockWidget.__init__(self, parent=parent)
mobj = moose.element(mobj)
#self.view = view = ObjectEditView(mobj)
self.view = view = ObjectEditView(mobj)
self.view_dict = {mobj: view}
base = QWidget()
layout = QVBoxLayout()
base.setLayout(layout)
layout.addWidget(self.view)
layout.addWidget(QTextEdit())
self.setWidget(base)
self.setWindowTitle('Edit: %s' % (mobj.path))
# self.view.colorDialog.colorSelected.connect(self.colorChangedEmit)
def setObject(self, mobj):
element = moose.element(mobj)
try:
view = self.view_dict[element]
except KeyError:
view = ObjectEditView(element)
self.view_dict[element] = view
view.model().objectNameChanged.connect(self.emitObjectNameChanged)
view.colorDialog.colorSelected.connect(lambda color: self.colorChanged.emit(element, color))
textEdit = QTextEdit()
view.setSizePolicy( QSizePolicy.Ignored
, QSizePolicy.Ignored
)
textEdit.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
base = QSplitter()
base.setOrientation(PyQt4.QtCore.Qt.Vertical)
layout = QVBoxLayout()
layout.addWidget(view)#, 0, 0)
if ( isinstance(mobj, moose.PoolBase)
or isinstance(mobj,moose.ReacBase)
or isinstance(mobj,moose.EnzBase)
) :
info = moose.Annotator(mobj.path +'/info')
textEdit.setText(QtCore.QString(info.getField('notes')))
textEdit.textChanged.connect(lambda : info.setField('notes', str(textEdit.toPlainText())))
layout.addWidget(textEdit)#,1,0)
# self.setRowHeight(notesIndex, self.rowHeight(notesIndex) * 3)
base.setLayout(layout)
# base.setSizes( [ view.height()
# , base.height() - view.height()
# ]
# )
# print("a =>", view.height())
# print("b =>", base.height())
# layout.setStretch(0,3)
# layout.setStretch(1,1)
# layout.setContentsMargins(QMargins(0,0,0,0))
self.setWidget(base)
self.setWindowTitle('Edit: %s' % (element.path))
view.update()
def emitObjectNameChanged(self, mobj):
self.objectNameChanged.emit(mobj)
def main():
app = QtGui.QApplication(sys.argv)
mainwin = QtGui.QMainWindow()
c = moose.Compartment("test")
view = ObjectEditView(c, undolen=3)
mainwin.setCentralWidget(view)
action = QtGui.QAction('Undo', mainwin)
action.setShortcut('Ctrl+z')
action.triggered.connect(view.model().undo)
mainwin.menuBar().addAction(action)
action = QtGui.QAction('Redo', mainwin)
action.setShortcut('Ctrl+y')
action.triggered.connect(view.model().redo)
mainwin.menuBar().addAction(action)
mainwin.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
# ojectedit.py ends here