~ubuntu-branches/ubuntu/karmic/eric/karmic

« back to all changes in this revision

Viewing changes to eric/ThirdParty/chartables/chartables.py

  • Committer: Bazaar Package Importer
  • Author(s): Scott Kitterman
  • Date: 2008-01-28 18:02:25 UTC
  • mfrom: (1.1.4 upstream)
  • Revision ID: james.westby@ubuntu.com-20080128180225-6nrox6yrworh2c4v
Tags: 4.0.4-1ubuntu1
* Add python-qt3 to build-depends becuase that's where Ubuntu puts 
  pyqtconfig
* Change maintainer to MOTU

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding: utf-8 -*-
 
2
 
 
3
"""
 
4
CharTables dialog
 
5
 
 
6
Provides various kinds of good-to-have-at-hand tables for charsets, colors
 
7
and entities.
 
8
 
 
9
 
 
10
Brief application overview:
 
11
 
 
12
The dialog is wrapped around a QTableView. QAbstractTableModels
 
13
are dynamically inserted at runtime. Each model is packed in a ModelFactory
 
14
wich can hold multiple models in multiple categories. All ModelFactories
 
15
are then handed out to the the controler of the dialog for further processing.
 
16
 
 
17
 
 
18
The dialog comes equipped to handle the Eric4 special functionality
 
19
of inserting the contents of a selected cell directly into at the current position
 
20
of the current editor, but may aswell be used as standalone dialog.
 
21
 
 
22
 
 
23
Note that chars may or may not get displayed properly. Also some
 
24
ranges in some encodings are left out for performance reasons.
 
25
 
 
26
"""
 
27
 
 
28
import sys, os
 
29
from PyQt4 import QtCore, QtGui
 
30
 
 
31
from Ui_chartables import Ui_CT_DialogCharTables
 
32
 
 
33
# import model factories
 
34
 
 
35
from chartables_model_options import Options
 
36
from chartables_controler import Controler
 
37
from chartables_models_charsets import CHARSET_MODEL_FACTORIES
 
38
from chartables_models_colors import COLOR_MODEL_FACTORIES
 
39
from chartables_models_entities import ENTITY_MODEL_FACTORIES
 
40
import chartables_lang
 
41
 
 
42
from chartables_lib.areatip import AreaTip
 
43
from chartables_lib.combobox import ComboBoxWithEditTipWrap
 
44
 
 
45
# TODO:
 
46
#
 
47
# in no particular order
 
48
#
 
49
# - anyone for more tables?
 
50
#
 
51
# - currently clipboard and drag offers only 'text/plain' format
 
52
# - some visual feedback would be nice to indicate an item was copied/inserted
 
53
#
 
54
# - tooltips for truncated items are not 100% accurate. Pretty hard to find out
 
55
#   when exactly Qt truncates strings in combos.
 
56
# - toltip for edit filed in combobox flaps out a tad to fast. Higher delay
 
57
#    would be nice
 
58
#
 
59
# - maybe an option to make the dialog stay topmost?
 
60
# - maybe a gridlines on/off option?
 
61
#
 
62
#
 
63
#***********************************************************************
 
64
# consts
 
65
#***********************************************************************
 
66
ICO_APP = 'chartables_small.png'
 
67
 
 
68
CFG_ORG_NAME = 'jUrner'
 
69
CFG_APP_NAME = 'CTDialogCharTables'
 
70
CFG_KEY_STATE = 'State'
 
71
CFG_KEY_GEOMETRY = 'Geometry'
 
72
CFG_KEY_FLAGS = 'Flags'
 
73
CFG_KEY_LOCALE = 'Locale'
 
74
 
 
75
 
 
76
ID_TAB = 'tabWidget'
 
77
ID_CHARSETTYPECOMBO = 'cmbCharsetType'
 
78
ID_CHARSETCOMBO = 'cmbCharset'
 
79
ID_COLORTYPECOMBO = 'cmbColorType'
 
80
ID_COLORCOMBO = 'cmbColor'
 
81
ID_ENTITYTYPECOMBO = 'cmbEntityType'
 
82
ID_ENTITYCOMBO = 'cmbEntity'
 
83
ID_TABLE = 'tableView'
 
84
 
 
85
ID_BUTTON_BOX = 'buttonBox'
 
86
ID_BTCOPY = 'btCopy'
 
87
ID_BTINSERT = 'btInsert'     # special button for Eric4
 
88
 
 
89
 
 
90
 
 
91
MODEL_FACTORIES = (
 
92
    (CHARSET_MODEL_FACTORIES, ID_CHARSETTYPECOMBO, ID_CHARSETCOMBO),
 
93
    (COLOR_MODEL_FACTORIES, ID_COLORTYPECOMBO, ID_COLORCOMBO),
 
94
    (ENTITY_MODEL_FACTORIES, ID_ENTITYTYPECOMBO, ID_ENTITYCOMBO),
 
95
    )
 
96
    
 
97
 
 
98
CMB_MIN_CONTENTS_LEN = 5
 
99
 
 
100
#***********************************************************************
 
101
#
 
102
#***********************************************************************
 
103
class DialogCharTables(QtGui.QWidget, Ui_CT_DialogCharTables):
 
104
    """Main dialog"""
 
105
 
 
106
 
 
107
    def __init__(self, *args, **kwargs):
 
108
        """
 
109
        constructor
 
110
 
 
111
        @keyparam flagsEx CTFEX_* runtime flags
 
112
        @keyparam localeName if specified adjusts the language of the dialog
 
113
            to the specified language
 
114
        """
 
115
        QtGui.QWidget.__init__(self, *args)
 
116
 
 
117
        self.options = Options(self, flagsEx=kwargs.get('flagsEx', Options.CTFEX_NONE))
 
118
        localeName = kwargs.get('localeName', None)
 
119
 
 
120
        self.setupUi(localeName=localeName)
 
121
 
 
122
 
 
123
 
 
124
    def setupUi(self, localeName=None):
 
125
        """
 
126
        overwritten method to setup the user interface
 
127
 
 
128
        @param parent parent of the dialog
 
129
        """
 
130
 
 
131
        self.controler = None
 
132
 
 
133
 
 
134
        # get settings
 
135
        settings = self.getSettingsObject()
 
136
        settingsState = settings.value(
 
137
                                    CFG_KEY_STATE,
 
138
                                    QtCore.QVariant('')
 
139
                                    ).toString()
 
140
        settingsFlags, ok = settings.value(
 
141
                                    CFG_KEY_FLAGS,
 
142
                                    QtCore.QVariant(Options.CTF_MASK_DEFAULT)
 
143
                                    ).toInt()
 
144
 
 
145
        self.options.flags = settingsFlags
 
146
 
 
147
        self.options.areatips = AreaTip(self)
 
148
 
 
149
        # adjust language
 
150
        if not self.options.flagsEx & self.options.CTFEX_NOTRANSLATE:
 
151
            if not localeName:
 
152
                settingsLocale = settings.value(
 
153
                                        CFG_KEY_LOCALE,
 
154
                                        QtCore.QVariant(self.options.localeName)
 
155
                                        ).toString()
 
156
                localeName = str(settingsLocale)
 
157
 
 
158
            self.options.language = chartables_lang.Language()
 
159
            if not self.options.language.hasLocaleName(localeName):
 
160
                localeName = self.options.language.getDefaultLocaleName()
 
161
            self.options.localeName =localeName
 
162
            self.options.language.installTranslator(self, localeName)
 
163
 
 
164
 
 
165
 
 
166
        Ui_CT_DialogCharTables.setupUi(self, self)
 
167
 
 
168
 
 
169
        # init main table
 
170
        table = self.controlById(ID_TABLE)
 
171
        table.verticalHeader().setVisible(False)
 
172
        table.setDragEnabled(True)
 
173
        table.setSelectionMode(table.SingleSelection)
 
174
        self.connect(
 
175
            table,
 
176
            QtCore.SIGNAL('activated(const QModelIndex&)'),
 
177
            self._onActivated
 
178
            )
 
179
 
 
180
        # init factories
 
181
        tab = self.controlById(ID_TAB)
 
182
        self.controler = Controler(table, tab, options=self.options)
 
183
        self.connect(
 
184
            self.controler,
 
185
            QtCore.SIGNAL('optionsDisplayed(const QWidget&, bool)'),
 
186
            self._onOptionsDisplayed
 
187
            )
 
188
        self.connect(
 
189
            self.controler,
 
190
            QtCore.SIGNAL('modelInserted(const QAbstractTableModel&)'),
 
191
            self._onModelInserted
 
192
            )
 
193
 
 
194
        for factories, idTypeCmb, idModelCmb in MODEL_FACTORIES:
 
195
            cmbType = self.controlById(idTypeCmb)
 
196
            cmbModel = self.controlById(idModelCmb)
 
197
 
 
198
            # strings may be long here, so truncate if necessary
 
199
            # and show tooltips if necessary
 
200
            cmbModel.setMinimumContentsLength(CMB_MIN_CONTENTS_LEN)
 
201
            cmbModel.setSizeAdjustPolicy(cmbModel.AdjustToMinimumContentsLength)
 
202
            ComboBoxWithEditTipWrap(cmbModel)
 
203
 
 
204
            self.controler.newFactory(factories, cmbType, cmbModel)
 
205
 
 
206
 
 
207
        # init buttons
 
208
        buttonBox = self.controlById(ID_BUTTON_BOX)
 
209
            
 
210
        btCopy = self.controlById(ID_BTCOPY)
 
211
        buttonBox.addButton(btCopy, buttonBox.ActionRole)
 
212
        btCopy.setEnabled(False)
 
213
        self.connect(btCopy, QtCore.SIGNAL('clicked()'), self._onBtCopyClicked)
 
214
 
 
215
        # init Eric4 special to handle 'Insert At' button and QSettings
 
216
        btInsert = self.controlById(ID_BTINSERT)
 
217
        buttonBox.addButton(btInsert, buttonBox.ActionRole)
 
218
        btInsert.setEnabled(False)
 
219
        btInsert.setVisible(False)
 
220
        
 
221
 
 
222
        # throw application icon on the caption
 
223
        fpath = os.path.join(os.path.split(__file__)[0], ICO_APP)
 
224
        if os.path.isfile(fpath):
 
225
            ico = QtGui.QIcon(fpath)
 
226
            if not ico.isNull():
 
227
                self.setWindowIcon(ico)
 
228
 
 
229
                
 
230
        # restore state
 
231
        self.controler.restoreState(str(settingsState))
 
232
        v = settings.value(CFG_KEY_GEOMETRY)
 
233
        if v.isValid():
 
234
            self.restoreGeometry(v.toByteArray())
 
235
        
 
236
 
 
237
 
 
238
 
 
239
    def closeEvent(self, evt):
 
240
        """protected slot called when the dialog is closed"""
 
241
        settings = self.getSettingsObject()
 
242
        settings.setValue(CFG_KEY_STATE, QtCore.QVariant(self.controler.saveState()))
 
243
        settings.setValue(CFG_KEY_FLAGS, QtCore.QVariant(self.options.flags))
 
244
        settings.setValue(CFG_KEY_LOCALE, QtCore.QVariant(self.options.localeName))
 
245
        settings.setValue(CFG_KEY_GEOMETRY, QtCore.QVariant(self.saveGeometry()))
 
246
 
 
247
 
 
248
    def getSettingsObject(self):
 
249
        """public method to return the QSettings instance for the dialog"""
 
250
        return QtCore.QSettings(
 
251
                    CFG_ORG_NAME,
 
252
                    CFG_APP_NAME,
 
253
                    self
 
254
                    )
 
255
 
 
256
 
 
257
    def _getCurrentModelCellText(self):
 
258
        """protected method to return content (string) of the current index in
 
259
        the main table
 
260
        """
 
261
        index = self.controlById(ID_TABLE).selectionModel().currentIndex()
 
262
        if index.isValid():
 
263
            v = index.data()
 
264
            if v.isValid():
 
265
                return v.toString()
 
266
        return ''
 
267
 
 
268
 
 
269
    def _enableSelectionButtons(self, flag):
 
270
        """protected slot to enable/disable buttons acting on the current selection"""
 
271
        self.controlById(ID_BTCOPY).setEnabled(flag)
 
272
 
 
273
 
 
274
    def _clipCopy(self, text):
 
275
        """protected method to copy a chunk of text to the clipboard"""
 
276
        if text:
 
277
            clipb = QtGui.QApplication.clipboard()
 
278
            clipb.setText(text, clipb.Clipboard)
 
279
            if clipb.supportsSelection():
 
280
                clipb.setText(text, clipb.Selection)
 
281
 
 
282
 
 
283
    def _onBtCopyClicked(self):
 
284
        """protected slot called when the Copy button is hit"""
 
285
        self._clipCopy(self._getCurrentModelCellText())
 
286
 
 
287
 
 
288
    def _onActivated(self, index):
 
289
        """protected slot to copy selected cell to clipboard (enter or doubleclick)"""
 
290
        self._clipCopy(self._getCurrentModelCellText())
 
291
 
 
292
 
 
293
    def _onOptionsDisplayed(self, optionsWidget, flag):
 
294
        """protected slot called when the options tab is displayed"""
 
295
        method = flag and self.connect or self.disconnect
 
296
        method(
 
297
            optionsWidget,
 
298
            QtCore.SIGNAL('languageChanged(QString&)'),
 
299
            self.translate
 
300
            )
 
301
 
 
302
 
 
303
    def _onModelInserted(self, model):
 
304
        """protected slot called when the current model changes"""
 
305
 
 
306
        # we are intersted here in selection changes
 
307
        table = self.controlById(ID_TABLE)
 
308
        selectionModel = table.selectionModel()
 
309
        table.connect(
 
310
                selectionModel,
 
311
                QtCore.SIGNAL('selectionChanged(const QItemSelection&, const QItemSelection&)'),
 
312
                self._onSelectionChanged
 
313
                )
 
314
        self._enableSelectionButtons(False)
 
315
 
 
316
 
 
317
    def _onSelectionChanged(self, selected, deselected):
 
318
        """protected slot called when the selection of the main table changes"""
 
319
 
 
320
        has_selection = False
 
321
        indexes = selected.indexes()
 
322
        if indexes:
 
323
            v = indexes[0].data()
 
324
            if v.isValid():
 
325
                if v.toString():
 
326
                    has_selection = True
 
327
        self._enableSelectionButtons(has_selection)
 
328
 
 
329
 
 
330
    def translate(self, localeName):
 
331
        """translates the user interface according to the specified localeName
 
332
 
 
333
        @param localeName (string, QString) name of the locale like 'en' or 'de'
 
334
 
 
335
        If no translation is found matching the specified localeName a default
 
336
        the user interface is translated to a default language
 
337
        """
 
338
        if not self.options.flagsEx & self.options.CTFEX_NOTRANSLATE:
 
339
            localeName = str(localeName)
 
340
            self.options.localeName = localeName
 
341
            self.options.language.installTranslator(self, localeName)
 
342
        Ui_CT_DialogCharTables.retranslateUi(self, self)
 
343
        self.controler.retranslate()
 
344
 
 
345
 
 
346
 
 
347
    def controlById(self, idControl):
 
348
        """
 
349
        convenience method to return a contol given its id
 
350
 
 
351
        @param idControl actually the name of the control as specified in designer
 
352
        """
 
353
        return getattr(self, idControl)
 
354
 
 
355
 
 
356
 
 
357
 
 
358
#***********************************************************************
 
359
#
 
360
#***********************************************************************
 
361
if __name__ == '__main__':
 
362
    app = QtGui.QApplication(sys.argv)
 
363
    dlg = DialogCharTables()
 
364
    dlg.show()
 
365
    res = app.exec_()
 
366
    sys.exit(res)
 
367
 
 
368
 
 
369
 
 
370