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
|
'''
Task Coach - Your friendly task manager
Copyright (C) 2011 Task Coach developers <developers@taskcoach.org>
Task Coach 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 of the License, or
(at your option) any later version.
Task Coach 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. If not, see <http://www.gnu.org/licenses/>.
'''
from taskcoachlib import meta
from taskcoachlib.i18n import _
import chardet
import wx
import csv
import tempfile
import wx.grid as gridlib
import wx.wizard as wiz
class CSVDialect(csv.Dialect):
def __init__(self, delimiter=',', quotechar='"', doublequote=True, escapechar=''):
self.delimiter = delimiter
self.quotechar = quotechar
self.quoting = csv.QUOTE_MINIMAL
self.lineterminator = '\r\n'
self.doublequote = doublequote
self.escapechar = escapechar
csv.Dialect.__init__(self)
class CSVImportOptionsPage(wiz.WizardPageSimple):
def __init__(self, filename, *args, **kwargs):
super(CSVImportOptionsPage, self).__init__(*args, **kwargs)
self.delimiter = wx.Choice(self, wx.ID_ANY)
self.delimiter.Append(_('Comma'))
self.delimiter.Append(_('Tab'))
self.delimiter.Append(_('Space'))
self.delimiter.Append(_('Colon'))
self.delimiter.Append(_('Semicolon'))
self.delimiter.Append(_('Pipe'))
self.delimiter.SetSelection(0)
self.date = wx.Choice(self)
self.date.Append(_('DD/MM (day first)'))
self.date.Append(_('MM/DD (month first)'))
self.date.SetSelection(0)
self.quoteChar = wx.Choice(self, wx.ID_ANY)
self.quoteChar.Append(_('Simple quote'))
self.quoteChar.Append(_('Double quote'))
self.quoteChar.SetSelection(1)
self.quotePanel = wx.Panel(self, wx.ID_ANY)
self.doubleQuote = wx.RadioButton(self.quotePanel, wx.ID_ANY, _('Double it'))
self.doubleQuote.SetValue(True)
self.escapeQuote = wx.RadioButton(self.quotePanel, wx.ID_ANY, _('Escape with'))
self.escapeChar = wx.TextCtrl(self.quotePanel, wx.ID_ANY, '\\', size=(50, -1))
self.escapeChar.Enable(False)
self.escapeChar.SetMaxLength(1)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
hsizer.Add(self.doubleQuote, 1, wx.ALL, 3)
hsizer.Add(self.escapeQuote, 1, wx.ALL, 3)
hsizer.Add(self.escapeChar, 1, wx.ALL, 3)
self.quotePanel.SetSizer(hsizer)
self.importSelectedRowsOnly = wx.CheckBox(self, wx.ID_ANY, _('Import only the selected rows'))
self.importSelectedRowsOnly.SetValue(False)
self.hasHeaders = wx.CheckBox(self, wx.ID_ANY, _('First line describes fields'))
self.hasHeaders.SetValue(True)
self.grid = gridlib.Grid(self)
self.grid.SetRowLabelSize(0)
self.grid.SetColLabelSize(0)
self.grid.CreateGrid(0, 0)
self.grid.EnableEditing(False)
self.grid.SetSelectionMode(self.grid.wxGridSelectRows)
vsizer = wx.BoxSizer(wx.VERTICAL)
gridSizer = wx.FlexGridSizer(0, 2)
gridSizer.Add(wx.StaticText(self, wx.ID_ANY, _('Delimiter')), 0,
wx.ALIGN_CENTRE_VERTICAL | wx.ALL, 3)
gridSizer.Add(self.delimiter, 0, wx.ALL, 3)
gridSizer.Add(wx.StaticText(self, wx.ID_ANY, _('Date format')), 0,
wx.ALIGN_CENTER_VERTICAL | wx.ALL, 3)
gridSizer.Add(self.date, 0, wx.ALL, 3)
gridSizer.Add(wx.StaticText(self, wx.ID_ANY, _('Quote character')), 0,
wx.ALIGN_CENTRE_VERTICAL | wx.ALL, 3)
gridSizer.Add(self.quoteChar, 0, wx.ALL, 3)
gridSizer.Add(wx.StaticText(self, wx.ID_ANY, _('Escape quote')), 0,
wx.ALIGN_CENTRE_VERTICAL | wx.ALL, 3)
gridSizer.Add(self.quotePanel, 0, wx.ALL, 3)
gridSizer.Add(self.importSelectedRowsOnly, 0, wx.ALL, 3)
gridSizer.Add((0, 0))
gridSizer.Add(self.hasHeaders, 0, wx.ALL, 3)
gridSizer.Add((0, 0))
gridSizer.AddGrowableCol(1)
vsizer.Add(gridSizer, 0, wx.EXPAND | wx.ALL, 3)
vsizer.Add(self.grid, 1, wx.EXPAND | wx.ALL, 3)
self.SetSizer(vsizer)
self.headers = None
self.filename = filename
self.encoding = chardet.detect(file(filename, 'rb').read())['encoding']
self.OnOptionChanged(None)
wx.EVT_CHOICE(self.delimiter, wx.ID_ANY, self.OnOptionChanged)
wx.EVT_CHOICE(self.quoteChar, wx.ID_ANY, self.OnOptionChanged)
wx.EVT_CHECKBOX(self.importSelectedRowsOnly, wx.ID_ANY, self.OnOptionChanged)
wx.EVT_CHECKBOX(self.hasHeaders, wx.ID_ANY, self.OnOptionChanged)
wx.EVT_RADIOBUTTON(self.doubleQuote, wx.ID_ANY, self.OnOptionChanged)
wx.EVT_RADIOBUTTON(self.escapeQuote, wx.ID_ANY, self.OnOptionChanged)
wx.EVT_TEXT(self.escapeChar, wx.ID_ANY, self.OnOptionChanged)
def OnOptionChanged(self, event): # pylint: disable=W0613
self.escapeChar.Enable(self.escapeQuote.GetValue())
if self.filename is None:
self.grid.SetRowLabelSize(0)
self.grid.SetColLabelSize(0)
if self.grid.GetNumberCols():
self.grid.DeleteRows(0, self.grid.GetNumberRows())
self.grid.DeleteCols(0, self.grid.GetNumberCols())
else:
if self.doubleQuote.GetValue():
doublequote = True
escapechar = ''
else:
doublequote = False
escapechar = self.escapeChar.GetValue().encode('UTF-8')
self.dialect = CSVDialect(delimiter={0: ',', 1: '\t', 2: ' ', 3: ':', 4: ';', 5: '|'}[self.delimiter.GetSelection()],
quotechar={0: "'", 1: '"'}[self.quoteChar.GetSelection()],
doublequote=doublequote, escapechar=escapechar)
fp = tempfile.TemporaryFile()
try:
fp.write(file(self.filename, 'rU').read().decode(self.encoding).encode('UTF-8'))
fp.seek(0)
reader = csv.reader(fp, dialect=self.dialect)
if self.hasHeaders.GetValue():
self.headers = [header.decode('UTF-8') for header in reader.next()]
else:
# In some cases, empty fields are omitted if they're at the end...
hsize = 0
for line in reader:
hsize = max(hsize, len(line))
self.headers = [_('Field #%d') % idx for idx in xrange(hsize)]
fp.seek(0)
reader = csv.reader(fp, dialect=self.dialect)
if self.grid.GetNumberCols():
self.grid.DeleteRows(0, self.grid.GetNumberRows())
self.grid.DeleteCols(0, self.grid.GetNumberCols())
self.grid.InsertCols(0, len(self.headers))
self.grid.SetColLabelSize(20)
for idx, header in enumerate(self.headers):
self.grid.SetColLabelValue(idx, header)
lineno = 0
for line in reader:
self.grid.InsertRows(lineno, 1)
for idx, value in enumerate(line):
if idx < self.grid.GetNumberCols():
self.grid.SetCellValue(lineno, idx, value.decode('UTF-8'))
lineno += 1
finally:
fp.close()
def GetOptions(self):
return dict(dialect=self.dialect,
dayfirst=self.date.GetSelection() == 0,
importSelectedRowsOnly=self.importSelectedRowsOnly.GetValue(),
selectedRows=self.GetSelectedRows(),
hasHeaders=self.hasHeaders.GetValue(),
filename=self.filename,
encoding=self.encoding,
fields=self.headers)
def GetSelectedRows(self):
startRows = [row for row, dummy_column in self.grid.GetSelectionBlockTopLeft()]
stopRows = [row for row, dummy_column in self.grid.GetSelectionBlockBottomRight()]
selectedRows = []
for startRow, stopRow in zip(startRows, stopRows):
selectedRows.extend(range(startRow, stopRow + 1))
return selectedRows
def CanGoNext(self):
if self.filename is not None:
self.GetNext().SetOptions(self.GetOptions())
return True, None
return False, _('Please select a file.')
class CSVImportMappingPage(wiz.WizardPageSimple):
def __init__(self, *args, **kwargs):
super(CSVImportMappingPage, self).__init__(*args, **kwargs)
# (field name, multiple values allowed)
self.fields = [
(_('None'), True),
(_('ID'), False),
(_('Subject'), False),
(_('Description'), True),
(_('Category'), True),
(_('Priority'), False),
(_('Planned start date'), False),
(_('Due date'), False),
(_('Actual start date'), False),
(_('Completion date'), False),
(_('Reminder date'), False),
(_('Budget'), False),
(_('Fixed fee'), False),
(_('Hourly fee'), False),
(_('Percent complete'), False),
]
self.choices = []
self.interior = wx.ScrolledWindow(self)
self.interior.EnableScrolling(False, True)
self.interior.SetScrollRate(10, 10)
sizer = wx.BoxSizer()
sizer.Add(self.interior, 1, wx.EXPAND)
self.SetSizer(sizer)
def SetOptions(self, options):
self.options = options
if self.interior.GetSizer():
self.interior.GetSizer().Clear(True)
for child in self.interior.GetChildren():
self.interior.RemoveChild(child)
self.choices = []
gsz = wx.FlexGridSizer(0, 2, 4, 2)
gsz.Add(wx.StaticText(self.interior, wx.ID_ANY, _('Column header in CSV file')))
gsz.Add(wx.StaticText(self.interior, wx.ID_ANY, _('%s attribute') % meta.name))
gsz.AddSpacer((3, 3))
gsz.AddSpacer((3, 3))
tcFieldNames = [field[0] for field in self.fields]
for fieldName in options['fields']:
gsz.Add(wx.StaticText(self.interior, wx.ID_ANY, fieldName), flag=wx.ALIGN_CENTER_VERTICAL)
choice = wx.Choice(self.interior, wx.ID_ANY)
for tcFieldName in tcFieldNames:
choice.Append(tcFieldName)
choice.SetSelection(self.findFieldName(fieldName, tcFieldNames))
self.choices.append(choice)
gsz.Add(choice, flag=wx.ALIGN_CENTER_VERTICAL)
gsz.AddGrowableCol(1)
self.interior.SetSizer(gsz)
gsz.Layout()
def findFieldName(self, fieldName, fieldNames):
def fieldNameIndex(fieldName, fieldNames):
return fieldNames.index(fieldName) if fieldName in fieldNames else 0
index = fieldNameIndex(fieldName, fieldNames)
return index if index else fieldNameIndex(fieldName[:6], [fieldName[:6] for fieldName in fieldNames])
def CanGoNext(self):
wrongFields = []
countNotNone = 0
for index, (fieldName, canMultiple) in enumerate(self.fields):
count = 0
for choice in self.choices:
if choice.GetSelection() == index:
count += 1
if choice.GetSelection() != 0:
countNotNone += 1
if count > 1 and not canMultiple:
wrongFields.append(fieldName)
if countNotNone == 0:
return False, _('No field mapping.')
if len(wrongFields) == 1:
return False, _('The "%s" field cannot be selected several times.') % wrongFields[0]
if len(wrongFields):
return False, _('The fields %s cannot be selected several times.') % ', '.join(['"%s"' % fieldName for fieldName in wrongFields])
return True, None
def GetOptions(self):
options = dict(self.options)
options['mappings'] = [self.fields[choice.GetSelection()][0] for choice in self.choices]
return options
class CSVImportWizard(wiz.Wizard):
def __init__(self, filename, *args, **kwargs):
kwargs['style'] = wx.RESIZE_BORDER | wx.DEFAULT_DIALOG_STYLE
super(CSVImportWizard, self).__init__(*args, **kwargs)
self.optionsPage = CSVImportOptionsPage(filename, self)
self.mappingPage = CSVImportMappingPage(self)
self.optionsPage.SetNext(self.mappingPage)
self.mappingPage.SetPrev(self.optionsPage)
self.SetPageSize((600, -1)) # I know this is obsolete but it's the only one that works...
wiz.EVT_WIZARD_PAGE_CHANGING(self, wx.ID_ANY, self.OnPageChanging)
wiz.EVT_WIZARD_PAGE_CHANGED(self, wx.ID_ANY, self.OnPageChanged)
def OnPageChanging(self, event):
if event.GetDirection():
can, msg = event.GetPage().CanGoNext()
if not can:
wx.MessageBox(msg, _('Information'), wx.OK)
event.Veto()
def OnPageChanged(self, event):
if event.GetPage() == self.optionsPage:
pass # XXXTODO
def RunWizard(self):
return super(CSVImportWizard, self).RunWizard(self.optionsPage)
def GetOptions(self):
return self.mappingPage.GetOptions()
|