Delegates are used for FK display. NOTE: CORE DUMP ON EXIT
[ipypbx] / src / ipypbx / controllers.py
1 # Copyright (c) Stas Shtin, 2010
2
3 # This file is part of IPyPBX.
4
5 # IPyPBX is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9
10 # IPyPBX is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License
16 # along with IPyPBX.  If not, see <http://www.gnu.org/licenses/>.
17
18 from PyQt4 import QtCore, QtGui, QtSql
19
20
21 class BaseController(QtCore.QObject):
22     """
23     Base class for other controllers.
24
25     Doesn't do anything useful on its own.
26     """
27     # TODO: possibly use a separate class for options and a meta-class.
28     fields = ()
29     view_list_fields = ()
30     view_display_fields = ()
31     view_display_fields_hidden = 'ID', 'Connection ID'
32     is_bound_to_connection = True
33     relations = ()
34     delegate = None
35     
36     def __init__(self, model=None, view_list=None, view_display=None, parent=None, views=None):
37         super(BaseController, self).__init__(parent=parent)
38
39         self.views = views
40         
41         # Find out base name.
42         classname = self.__class__.__name__
43         self.basename = (
44             classname[:-10] if classname.endswith('Controller')
45             else classname)
46         self.basename = self.basename[0].lower() + self.basename[1:]
47
48         # Are we given an existing model?
49         if model:
50             self.model = model
51         # Otherwise initialize a new model.
52         else:
53             self.model = QtSql.QSqlRelationalTableModel(parent)
54             self.model.setTable('ipypbxweb_%s' % self.basename.lower())
55             self.model.setEditStrategy(self.model.OnRowChange)
56
57             # Create model header from fields list.
58             for i, field in enumerate(self.fields):
59                 self.model.setHeaderData(
60                     i, QtCore.Qt.Horizontal,
61                     QtCore.QVariant(QtGui.QApplication.translate(
62                         "MainWindow", field, None,
63                         QtGui.QApplication.UnicodeUTF8)))
64
65             # Fetch model data.
66             self.model.select()
67
68         # Are we given an existing view list?
69         if view_list:
70             self.view_list = view_list
71         # Otherwise get view list from the parent.            
72         else:
73             self.view_list = getattr(views, self.basename + 'ViewList')
74             self.view_list.setModel(self.model)
75
76             # Hide fields not meant for display.
77             for i, field in enumerate(self.fields):
78                 if field not in self.view_list_fields:
79                     self.view_list.hideColumn(i)
80
81             # Stretch headers to fill all available width.
82             self.view_list.setSelectionMode(QtGui.QTableView.SingleSelection)
83             self.view_list.setSelectionBehavior(QtGui.QTableView.SelectRows)
84             self.view_list.resizeColumnsToContents()
85             self.view_list.resizeRowsToContents()
86             self.view_list.horizontalHeader().setStretchLastSection(True)
87
88         # Select first row.
89         self.view_list.selectRow(0)
90
91         # Are we given an existing view display?
92         if view_display:
93             self.view_display = view_display
94         # Otherwise get view display from the parent.
95         else:
96             self.view_display = QtGui.QDataWidgetMapper(parent)
97             self.view_display.setModel(self.model)
98
99             display_fields = self.getDisplayFields()
100             
101             for i, field in enumerate(self.fields):
102                 if field in display_fields:
103                     field_widget = self.getFieldWidget(field)
104                     self.view_display.addMapping(field_widget, i)
105
106         # Set relations for model & view display.
107         if self.relations:
108             self.delegate = QtSql.QSqlRelationalDelegate(self)
109             self.view_display.setItemDelegate(self.delegate)
110
111             for data in self.relations:
112                 column, name, table, display = data                
113                 column_index = self.model.fieldIndex(column)
114
115                 # SetRelation screws table data filtering?
116                 self.model.setRelation(
117                     column_index,
118                     QtSql.QSqlRelation('ipypbxweb_%s' % table, 'id', display))
119                 #self.model.select()
120
121                 rel = self.model.relationModel(column_index)
122
123                 widget = self.getFieldWidget(name)
124                 widget.setModel(self.parent().controllers[table].model)
125                 widget.setModelColumn(rel.fieldIndex(display))
126                 #widget.setItemDelegate(self.delegate)
127
128
129         # Select first row in the view list.
130         self.view_display.toFirst()
131         
132         # Register signals for this controller.
133         for data in self.getSignalsData():
134             if len(data) == 3:
135                 sender, signal, receiver = data
136                 QtCore.QObject.connect(sender, QtCore.SIGNAL(signal), receiver)
137             elif len(data) == 4:
138                 sender, signal, receiver, slot = data
139                 QtCore.QObject.connect(
140                     sender, QtCore.SIGNAL(signal), receiver, QtCore.SLOT(slot))
141                                        
142     def getFieldWidget(self, field):
143         """
144         Return widget for given field name.
145         """
146         return getattr(
147             self.views,
148             self.basename + ''.join(word.capitalize()
149                                     for word in field.split(' ')))
150
151     def getDisplayFields(self):
152         """
153         Return list of display fields.
154         
155         If view_display_fields is not send, display all fields except
156         the first one that is usually the ID.
157         """
158         return [
159             field for field in self.fields
160             if not field in self.view_display_fields_hidden]        
161
162     def getSignalsData(self):
163         """
164         Default signals built from controller's base name.
165         """
166         # Default signals handle row selection, Add and Save buttons.
167         return [
168             (getattr(self.views, self.basename + 'Add'), 'clicked()', self.add),
169             (self.view_list.selectionModel(),
170              'currentRowChanged(QModelIndex,QModelIndex)',
171              self.view_display, 'setCurrentModelIndex(QModelIndex)'),
172             (getattr(self.views, self.basename + 'Save'), 'clicked()',
173              self.save)]
174
175     def add(self):
176         """
177         Add new object.
178         """
179         # Add a new row to list view.
180         num_rows = self.model.rowCount()
181         self.model.insertRows(num_rows, 1)
182         self.view_list.selectRow(num_rows)
183
184         # Disable adding more than one row.
185         self.getFieldWidget('Add').setEnabled(False)
186
187         # Focust to the first displayed field.
188         self.getFieldWidget(self.getDisplayFields()[0]).setFocus()
189
190     def save(self):
191         """
192         Save to database.
193         """
194         self.view_display.submit()
195         self.getFieldWidget('Add').setEnabled(True)
196
197
198 class ConnectionController(BaseController):
199     """
200     Connections controller.
201     """
202     fields = (
203         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
204         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Name'),
205         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Local IP Address'),
206         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Local Port'),
207         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Freeswitch IP Address'),
208         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Freeswitch Port'))
209     view_list_fields = 'Name', 'Freeswitch IP Address', 'Freeswitch Port'
210
211
212 class ConnectionChangeListenerController(BaseController):
213     """
214     Mixin class for reacting on connection change.
215     """
216     def getSignalsData(self):
217         """
218         Listen to connection change signal.
219         """
220         connection_controller = self.parent().controllers['connection']
221
222         signals = [
223             (connection_controller.view_list.selectionModel(),
224              'currentRowChanged(QModelIndex,QModelIndex)',
225              self.connectionChange),
226             (self.model, 'primeInsert(int,QSqlRecord&)',
227              self.setConnectionId)] 
228         signals.extend(super(
229             ConnectionChangeListenerController, self).getSignalsData())
230         return signals
231         
232     def connectionChange(self, index):
233         """
234         Connection change handler.
235
236         Filters table by a new connection ID and stores last connection ID
237         locally.
238         """
239         if index.row() != -1:
240             connection_id, ok = index.model().data(
241                 index.sibling(index.row(), 0)).toInt()
242             self.connection_id = connection_id
243             self.model.setFilter('ipypbxweb_%s.connection_id = %i' % (self.basename, connection_id))
244             self.view_list.selectRow(0)
245             if not self.model.rowCount():
246                 self.add()
247
248     def setConnectionId(self, row, record):
249         record.setValue('connection_id', self.connection_id)
250
251         
252 class SipProfileController(ConnectionChangeListenerController):
253     """
254     SIP Profile controller.
255     """
256     fields = (
257         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
258         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Connection ID'),
259         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Name'),
260         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'External RTP IP'),
261         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'External SIP IP'),
262         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'RTP IP'),
263         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'SIP IP'),
264         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'SIP Port'),
265         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Accept Blind Registration'),
266         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Authenticate Calls'),
267         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Is Active'))
268     view_list_fields = 'Name', 'SIP IP', 'SIP Port'
269     
270
271 class DomainController(ConnectionChangeListenerController):
272     """
273     Domain controller.
274     """
275     fields = (
276         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
277         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Connection ID'),
278         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'SIP Profile ID'),
279         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Host Name'),
280         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Is Active'))
281     view_list_fields = 'SIP Profile ID', 'Host Name'
282     relations = (('sip_profile_id', 'SIP Profile ID', 'sipprofile', 'name'),)
283     
284
285 class GatewayController(ConnectionChangeListenerController):
286     """
287     Gateway controller.
288     """
289     fields = (
290         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
291         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Connection ID'),
292         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'SIP Profile ID'),
293         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Name'),
294         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Username'),
295         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Password'),
296         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Realm'),
297         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'From Domain'),
298         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Expire In Seconds'),
299         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Retry In Seconds'),
300         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Caller ID In From Field'),
301         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Is Active'))
302     view_list_fields = 'SIP Profile ID', 'Name'
303     relations = (('sip_profile_id', 'SIP Profile ID', 'sipprofile', 'name'),)
304     
305
306 class EndpointController(ConnectionChangeListenerController):
307     """
308     Endpoint controller.
309     """
310     fields = (
311         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
312         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Connection ID'),
313         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'User ID'),
314         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Password'),
315         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Domain ID'),
316         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Is Active'))
317     view_list_fields = 'User ID', 'Domain ID'
318     relations = (('domain_id', 'Domain ID', 'domain', 'host_name'),)
319     
320
321 class ExtensionController(ConnectionChangeListenerController):
322     """
323     Extension controller.
324     """
325     fields = (
326         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'ID'),
327         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Connection ID'),
328         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Destination Match'),
329         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'XML Dialplan'),
330         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Domain ID'),
331         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Endpoint ID'),
332         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Authenticate Calls'),
333         QtCore.QT_TRANSLATE_NOOP('MainWindow', 'Is Active'))
334     view_list_fields = 'Destination Match',
335     relations = (
336         ('domain_id', 'Domain ID', 'domain', 'host_name'),
337         ('endpoint_id', 'Endpoint ID', 'endpoint', 'user_id'))
338