dialogs.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. """!
  2. @package dbmgr.dialogs
  3. @brief DBM-related dialogs
  4. List of classes:
  5. - dialogs::DisplayAttributesDialog
  6. - dialogs::ModifyTableRecord
  7. - dialogs::AddColumnDialog
  8. (C) 2007-2013 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Martin Landa <landa.martin gmail.com>
  12. @author Refactoring by Stepan Turek <stepan.turek seznam.cz> (GSoC 2012, mentor: Martin Landa)
  13. """
  14. import os
  15. import types
  16. from core import globalvar
  17. from core.utils import _
  18. import wx
  19. import wx.lib.scrolledpanel as scrolled
  20. from core.gcmd import RunCommand, GError
  21. from core.debug import Debug
  22. from core.settings import UserSettings
  23. from dbmgr.vinfo import VectorDBInfo, GetUnicodeValue
  24. from gui_core.widgets import IntegerValidator, FloatValidator
  25. class DisplayAttributesDialog(wx.Dialog):
  26. def __init__(self, parent, map,
  27. query = None, cats = None, line = None,
  28. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  29. pos = wx.DefaultPosition,
  30. action = "add", ignoreError = False):
  31. """!Standard dialog used to add/update/display attributes linked
  32. to the vector map.
  33. Attribute data can be selected based on layer and category number
  34. or coordinates.
  35. @param parent
  36. @param map vector map
  37. @param query query coordinates and distance (used for v.edit)
  38. @param cats {layer: cats}
  39. @param line feature id (requested for cats)
  40. @param style
  41. @param pos
  42. @param action (add, update, display)
  43. @param ignoreError True to ignore errors
  44. """
  45. self.parent = parent # mapdisplay.BufferedWindow
  46. self.map = map
  47. self.action = action
  48. # ids/cats of selected features
  49. # fid : {layer : cats}
  50. self.cats = {}
  51. self.fid = -1 # feature id
  52. # get layer/table/column information
  53. self.mapDBInfo = VectorDBInfo(self.map)
  54. layers = self.mapDBInfo.layers.keys() # get available layers
  55. # check if db connection / layer exists
  56. if len(layers) <= 0:
  57. if not ignoreError:
  58. dlg = wx.MessageDialog(parent = self.parent,
  59. message = _("No attribute table found.\n\n"
  60. "Do you want to create a new attribute table "
  61. "and defined a link to vector map <%s>?") % self.map,
  62. caption = _("Create table?"),
  63. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  64. if dlg.ShowModal() == wx.ID_YES:
  65. lmgr = self.parent.lmgr
  66. lmgr.OnShowAttributeTable(event = None, selection = 'layers')
  67. dlg.Destroy()
  68. self.mapDBInfo = None
  69. wx.Dialog.__init__(self, parent = self.parent, id = wx.ID_ANY,
  70. title = "", style = style, pos = pos)
  71. # dialog body
  72. mainSizer = wx.BoxSizer(wx.VERTICAL)
  73. # notebook
  74. self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
  75. self.closeDialog = wx.CheckBox(parent = self, id = wx.ID_ANY,
  76. label = _("Close dialog on submit"))
  77. self.closeDialog.SetValue(True)
  78. if self.action == 'display':
  79. self.closeDialog.Enable(False)
  80. # feature id (text/choice for duplicates)
  81. self.fidMulti = wx.Choice(parent = self, id = wx.ID_ANY,
  82. size = (150, -1))
  83. self.fidMulti.Bind(wx.EVT_CHOICE, self.OnFeature)
  84. self.fidText = wx.StaticText(parent = self, id = wx.ID_ANY)
  85. self.noFoundMsg = wx.StaticText(parent = self, id = wx.ID_ANY,
  86. label = _("No attributes found"))
  87. self.UpdateDialog(query = query, cats = cats)
  88. # set title
  89. if self.action == "update":
  90. self.SetTitle(_("Update attributes"))
  91. elif self.action == "add":
  92. self.SetTitle(_("Define attributes"))
  93. else:
  94. self.SetTitle(_("Display attributes"))
  95. # buttons
  96. btnCancel = wx.Button(self, wx.ID_CANCEL)
  97. btnReset = wx.Button(self, wx.ID_UNDO, _("&Reload"))
  98. btnSubmit = wx.Button(self, wx.ID_OK, _("&Submit"))
  99. if self.action == 'display':
  100. btnSubmit.Enable(False)
  101. btnSizer = wx.StdDialogButtonSizer()
  102. btnSizer.AddButton(btnCancel)
  103. btnSizer.AddButton(btnReset)
  104. btnSizer.SetNegativeButton(btnReset)
  105. btnSubmit.SetDefault()
  106. btnSizer.AddButton(btnSubmit)
  107. btnSizer.Realize()
  108. mainSizer.Add(item = self.noFoundMsg, proportion = 0,
  109. flag = wx.EXPAND | wx.ALL, border = 5)
  110. mainSizer.Add(item = self.notebook, proportion = 1,
  111. flag = wx.EXPAND | wx.ALL, border = 5)
  112. fidSizer = wx.BoxSizer(wx.HORIZONTAL)
  113. fidSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
  114. label = _("Feature id:")),
  115. proportion = 0, border = 5,
  116. flag = wx.ALIGN_CENTER_VERTICAL)
  117. fidSizer.Add(item = self.fidMulti, proportion = 0,
  118. flag = wx.EXPAND | wx.ALL, border = 5)
  119. fidSizer.Add(item = self.fidText, proportion = 0,
  120. flag = wx.EXPAND | wx.ALL, border = 5)
  121. mainSizer.Add(item = fidSizer, proportion = 0,
  122. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  123. mainSizer.Add(item = self.closeDialog, proportion = 0, flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
  124. border = 5)
  125. mainSizer.Add(item = btnSizer, proportion = 0,
  126. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  127. # bindigs
  128. btnReset.Bind(wx.EVT_BUTTON, self.OnReset)
  129. btnSubmit.Bind(wx.EVT_BUTTON, self.OnSubmit)
  130. btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  131. self.SetSizer(mainSizer)
  132. mainSizer.Fit(self)
  133. # set min size for dialog
  134. w, h = self.GetBestSize()
  135. w += 50
  136. if h < 200:
  137. self.SetMinSize((w, 200))
  138. else:
  139. self.SetMinSize((w, h))
  140. if self.notebook.GetPageCount() == 0:
  141. Debug.msg(2, "DisplayAttributesDialog(): Nothing found!")
  142. ### self.mapDBInfo = None
  143. def OnSQLStatement(self, event):
  144. """!Update SQL statement"""
  145. pass
  146. def IsFound(self):
  147. """!Check for status
  148. @return True on attributes found
  149. @return False attributes not found
  150. """
  151. return bool(self.mapDBInfo and self.notebook.GetPageCount() > 0)
  152. def GetSQLString(self, updateValues = False):
  153. """!Create SQL statement string based on self.sqlStatement
  154. Show error message when invalid values are entered.
  155. If updateValues is True, update dataFrame according to values
  156. in textfields.
  157. """
  158. sqlCommands = []
  159. # find updated values for each layer/category
  160. for layer in self.mapDBInfo.layers.keys(): # for each layer
  161. table = self.mapDBInfo.GetTable(layer)
  162. key = self.mapDBInfo.GetKeyColumn(layer)
  163. columns = self.mapDBInfo.GetTableDesc(table)
  164. for idx in range(len(columns[key]['values'])): # for each category
  165. updatedColumns = []
  166. updatedValues = []
  167. for name in columns.keys():
  168. if name == key:
  169. cat = columns[name]['values'][idx]
  170. continue
  171. ctype = columns[name]['ctype']
  172. value = columns[name]['values'][idx]
  173. id = columns[name]['ids'][idx]
  174. try:
  175. newvalue = self.FindWindowById(id).GetValue()
  176. except:
  177. newvalue = self.FindWindowById(id).GetLabel()
  178. if newvalue:
  179. try:
  180. if ctype == int:
  181. newvalue = int(newvalue)
  182. elif ctype == float:
  183. newvalue = float(newvalue)
  184. except ValueError:
  185. GError(parent = self,
  186. message = _("Column <%(col)s>: Value '%(value)s' needs to be entered as %(type)s.") % \
  187. {'col' : name,
  188. 'value' : str(newvalue),
  189. 'type' : columns[name]['type'].lower()},
  190. showTraceback = False)
  191. sqlCommands.append(None)
  192. continue
  193. else:
  194. if self.action == 'add':
  195. continue
  196. if newvalue != value:
  197. updatedColumns.append(name)
  198. if not newvalue:
  199. updatedValues.append('NULL')
  200. else:
  201. if ctype != str:
  202. updatedValues.append(str(newvalue))
  203. else:
  204. updatedValues.append("'" + str(newvalue) + "'")
  205. columns[name]['values'][idx] = newvalue
  206. if self.action != "add" and len(updatedValues) == 0:
  207. continue
  208. if self.action == "add":
  209. sqlString = "INSERT INTO %s (%s," % (table, key)
  210. else:
  211. sqlString = "UPDATE %s SET " % table
  212. for idx in range(len(updatedColumns)):
  213. name = updatedColumns[idx]
  214. if self.action == "add":
  215. sqlString += name + ","
  216. else:
  217. sqlString += name + "=" + updatedValues[idx] + ","
  218. sqlString = sqlString[:-1] # remove last comma
  219. if self.action == "add":
  220. sqlString += ") VALUES (%s," % cat
  221. for value in updatedValues:
  222. sqlString += str(value) + ","
  223. sqlString = sqlString[:-1] # remove last comma
  224. sqlString += ")"
  225. else:
  226. sqlString += " WHERE %s=%s" % (key, cat)
  227. sqlCommands.append(sqlString)
  228. # for each category
  229. # for each layer END
  230. Debug.msg(3, "DisplayAttributesDialog.GetSQLString(): %s" % sqlCommands)
  231. return sqlCommands
  232. def OnReset(self, event = None):
  233. """!Reset form"""
  234. for layer in self.mapDBInfo.layers.keys():
  235. table = self.mapDBInfo.layers[layer]["table"]
  236. key = self.mapDBInfo.layers[layer]["key"]
  237. columns = self.mapDBInfo.tables[table]
  238. for idx in range(len(columns[key]['values'])):
  239. for name in columns.keys():
  240. type = columns[name]['type']
  241. value = columns[name]['values'][idx]
  242. if value is None:
  243. value = ''
  244. try:
  245. id = columns[name]['ids'][idx]
  246. except IndexError:
  247. id = wx.NOT_FOUND
  248. if name != key and id != wx.NOT_FOUND:
  249. self.FindWindowById(id).SetValue(str(value))
  250. def OnCancel(self, event):
  251. """!Cancel button pressed
  252. """
  253. frame = self.parent.parent
  254. frame.dialogs['attributes'] = None
  255. if hasattr(self, "digit"):
  256. self.parent.digit.GetDisplay().SetSelected([])
  257. if frame.IsAutoRendered():
  258. self.parent.UpdateMap(render = False)
  259. elif frame.IsAutoRendered():
  260. frame.RemoveQueryLayer()
  261. self.parent.UpdateMap(render = True)
  262. self.Close()
  263. def OnSubmit(self, event):
  264. """!Submit records"""
  265. layer = 1
  266. close = True
  267. enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
  268. if not enc and 'GRASS_DB_ENCODING' in os.environ:
  269. enc = os.environ['GRASS_DB_ENCODING']
  270. for sql in self.GetSQLString(updateValues = True):
  271. if not sql:
  272. close = False
  273. continue
  274. if enc:
  275. sql = sql.encode(enc)
  276. driver, database = self.mapDBInfo.GetDbSettings(layer)
  277. Debug.msg(1, "SQL: %s" % sql)
  278. RunCommand('db.execute',
  279. parent = self,
  280. quiet = True,
  281. input = '-',
  282. stdin = sql,
  283. driver = driver,
  284. database = database)
  285. layer += 1
  286. if close and self.closeDialog.IsChecked():
  287. self.OnCancel(event)
  288. def OnFeature(self, event):
  289. self.fid = int(event.GetString())
  290. self.UpdateDialog(cats = self.cats, fid = self.fid)
  291. def GetCats(self):
  292. """!Get id of selected vector object or 'None' if nothing selected
  293. @param id if true return ids otherwise cats
  294. """
  295. if self.fid < 0:
  296. return None
  297. return self.cats[self.fid]
  298. def GetFid(self):
  299. """!Get selected feature id"""
  300. return self.fid
  301. def UpdateDialog(self, map = None, query = None, cats = None, fid = -1,
  302. action = None):
  303. """!Update dialog
  304. @param map name of vector map
  305. @param query
  306. @param cats
  307. @param fid feature id
  308. @param action add, update, display or None
  309. @return True if updated
  310. @return False
  311. """
  312. if action:
  313. self.action = action
  314. if action == 'display':
  315. enabled = False
  316. else:
  317. enabled = True
  318. self.closeDialog.Enable(enabled)
  319. self.FindWindowById(wx.ID_OK).Enable(enabled)
  320. if map:
  321. self.map = map
  322. # get layer/table/column information
  323. self.mapDBInfo = VectorDBInfo(self.map)
  324. if not self.mapDBInfo:
  325. return False
  326. self.mapDBInfo.Reset()
  327. layers = self.mapDBInfo.layers.keys() # get available layers
  328. # id of selected line
  329. if query: # select by position
  330. data = self.mapDBInfo.SelectByPoint(query[0],
  331. query[1])
  332. self.cats = {}
  333. if data and 'Layer' in data:
  334. idx = 0
  335. for layer in data['Layer']:
  336. layer = int(layer)
  337. if data['Id'][idx] is not None:
  338. tfid = int(data['Id'][idx])
  339. else:
  340. tfid = 0 # Area / Volume
  341. if not tfid in self.cats:
  342. self.cats[tfid] = {}
  343. if not layer in self.cats[tfid]:
  344. self.cats[tfid][layer] = []
  345. cat = int(data['Category'][idx])
  346. self.cats[tfid][layer].append(cat)
  347. idx += 1
  348. else:
  349. self.cats = cats
  350. if fid > 0:
  351. self.fid = fid
  352. elif len(self.cats.keys()) > 0:
  353. self.fid = self.cats.keys()[0]
  354. else:
  355. self.fid = -1
  356. if len(self.cats.keys()) == 1:
  357. self.fidMulti.Show(False)
  358. self.fidText.Show(True)
  359. if self.fid > 0:
  360. self.fidText.SetLabel("%d" % self.fid)
  361. else:
  362. self.fidText.SetLabel(_("Unknown"))
  363. else:
  364. self.fidMulti.Show(True)
  365. self.fidText.Show(False)
  366. choices = []
  367. for tfid in self.cats.keys():
  368. choices.append(str(tfid))
  369. self.fidMulti.SetItems(choices)
  370. self.fidMulti.SetStringSelection(str(self.fid))
  371. # reset notebook
  372. self.notebook.DeleteAllPages()
  373. for layer in layers: # for each layer
  374. if not query: # select by layer/cat
  375. if self.fid > 0 and layer in self.cats[self.fid]:
  376. for cat in self.cats[self.fid][layer]:
  377. nselected = self.mapDBInfo.SelectFromTable(layer,
  378. where = "%s=%d" % \
  379. (self.mapDBInfo.layers[layer]['key'],
  380. cat))
  381. else:
  382. nselected = 0
  383. # if nselected <= 0 and self.action != "add":
  384. # continue # nothing selected ...
  385. if self.action == "add":
  386. if nselected <= 0:
  387. if layer in self.cats[self.fid]:
  388. table = self.mapDBInfo.layers[layer]["table"]
  389. key = self.mapDBInfo.layers[layer]["key"]
  390. columns = self.mapDBInfo.tables[table]
  391. for name in columns.keys():
  392. if name == key:
  393. for cat in self.cats[self.fid][layer]:
  394. self.mapDBInfo.tables[table][name]['values'].append(cat)
  395. else:
  396. self.mapDBInfo.tables[table][name]['values'].append(None)
  397. else: # change status 'add' -> 'update'
  398. self.action = "update"
  399. table = self.mapDBInfo.layers[layer]["table"]
  400. key = self.mapDBInfo.layers[layer]["key"]
  401. columns = self.mapDBInfo.tables[table]
  402. for idx in range(len(columns[key]['values'])):
  403. for name in columns.keys():
  404. if name == key:
  405. cat = int(columns[name]['values'][idx])
  406. break
  407. # use scrolled panel instead (and fix initial max height of the window to 480px)
  408. panel = scrolled.ScrolledPanel(parent = self.notebook, id = wx.ID_ANY,
  409. size = (-1, 150))
  410. panel.SetupScrolling(scroll_x = False)
  411. self.notebook.AddPage(page = panel, text = " %s %d / %s %d" % (_("Layer"), layer,
  412. _("Category"), cat))
  413. # notebook body
  414. border = wx.BoxSizer(wx.VERTICAL)
  415. flexSizer = wx.FlexGridSizer (cols = 3, hgap = 3, vgap = 3)
  416. flexSizer.AddGrowableCol(2)
  417. # columns (sorted by index)
  418. names = [''] * len(columns.keys())
  419. for name in columns.keys():
  420. names[columns[name]['index']] = name
  421. for name in names:
  422. if name == key: # skip key column (category)
  423. continue
  424. vtype = columns[name]['type'].lower()
  425. ctype = columns[name]['ctype']
  426. if columns[name]['values'][idx] is not None:
  427. if columns[name]['ctype'] != types.StringType:
  428. value = str(columns[name]['values'][idx])
  429. else:
  430. value = columns[name]['values'][idx]
  431. else:
  432. value = ''
  433. colName = wx.StaticText(parent = panel, id = wx.ID_ANY,
  434. label = name)
  435. colType = wx.StaticText(parent = panel, id = wx.ID_ANY,
  436. label = "[%s]:" % vtype)
  437. colValue = wx.TextCtrl(parent = panel, id = wx.ID_ANY, value = value)
  438. colValue.SetName(name)
  439. if ctype == int:
  440. colValue.SetValidator(IntegerValidator())
  441. elif ctype == float:
  442. colValue.SetValidator(FloatValidator())
  443. self.Bind(wx.EVT_TEXT, self.OnSQLStatement, colValue)
  444. if self.action == 'display':
  445. colValue.SetWindowStyle(wx.TE_READONLY)
  446. flexSizer.Add(colName, proportion = 0,
  447. flag = wx.ALIGN_CENTER_VERTICAL)
  448. flexSizer.Add(colType, proportion = 0,
  449. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
  450. flexSizer.Add(colValue, proportion = 1,
  451. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  452. # add widget reference to self.columns
  453. columns[name]['ids'].append(colValue.GetId()) # name, type, values, id
  454. # for each attribute (including category) END
  455. border.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
  456. panel.SetSizer(border)
  457. # for each category END
  458. # for each layer END
  459. if self.notebook.GetPageCount() == 0:
  460. self.noFoundMsg.Show(True)
  461. else:
  462. self.noFoundMsg.Show(False)
  463. self.Layout()
  464. return True
  465. def SetColumnValue(self, layer, column, value):
  466. """!Set attrbute value
  467. @param column column name
  468. @param value value
  469. """
  470. table = self.mapDBInfo.GetTable(layer)
  471. columns = self.mapDBInfo.GetTableDesc(table)
  472. for key, col in columns.iteritems():
  473. if key == column:
  474. col['values'] = [col['ctype'](value),]
  475. break
  476. class ModifyTableRecord(wx.Dialog):
  477. def __init__(self, parent, title, data, keyEditable = (-1, True),
  478. id = wx.ID_ANY, style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  479. """!Dialog for inserting/updating table record
  480. @param data a list: [(column, value)]
  481. @param KeyEditable (id, editable?) indicates if textarea for key column
  482. is editable(True) or not
  483. """
  484. # parent -> VDigitWindow
  485. wx.Dialog.__init__(self, parent, id, title, style = style)
  486. self.CenterOnParent()
  487. self.keyId = keyEditable[0]
  488. box = wx.StaticBox(parent = self, id = wx.ID_ANY)
  489. box.Hide()
  490. self.dataPanel = scrolled.ScrolledPanel(parent = self, id = wx.ID_ANY,
  491. style = wx.TAB_TRAVERSAL)
  492. self.dataPanel.SetupScrolling(scroll_x = False)
  493. # buttons
  494. self.btnCancel = wx.Button(self, wx.ID_CANCEL)
  495. self.btnSubmit = wx.Button(self, wx.ID_OK, _("&Submit"))
  496. self.btnSubmit.SetDefault()
  497. # data area
  498. self.widgets = []
  499. cId = 0
  500. self.usebox = False
  501. self.cat = None
  502. winFocus = False
  503. for column, ctype, ctypeStr, value in data:
  504. if self.keyId == cId:
  505. self.cat = int(value)
  506. if not keyEditable[1]:
  507. self.usebox = True
  508. box.SetLabel(" %s %d " % (_("Category"), self.cat))
  509. box.Show()
  510. self.boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  511. cId += 1
  512. continue
  513. else:
  514. valueWin = wx.SpinCtrl(parent = self.dataPanel, id = wx.ID_ANY,
  515. value = value, min = -1e9, max = 1e9, size = (250, -1))
  516. else:
  517. valueWin = wx.TextCtrl(parent = self.dataPanel, id = wx.ID_ANY,
  518. value = value, size = (250, -1))
  519. if ctype == int:
  520. valueWin.SetValidator(IntegerValidator())
  521. elif ctype == float:
  522. valueWin.SetValidator(FloatValidator())
  523. if not winFocus:
  524. wx.CallAfter(valueWin.SetFocus)
  525. winFocus = True
  526. label = wx.StaticText(parent = self.dataPanel, id = wx.ID_ANY,
  527. label = column)
  528. ctype = wx.StaticText(parent = self.dataPanel, id = wx.ID_ANY,
  529. label = "[%s]:" % ctypeStr.lower())
  530. self.widgets.append((label.GetId(), ctype.GetId(), valueWin.GetId()))
  531. cId += 1
  532. self._layout()
  533. def _layout(self):
  534. """!Do layout"""
  535. sizer = wx.BoxSizer(wx.VERTICAL)
  536. # data area
  537. dataSizer = wx.FlexGridSizer(cols = 3, hgap = 3, vgap = 3)
  538. dataSizer.AddGrowableCol(2)
  539. for labelId, ctypeId, valueId in self.widgets:
  540. label = self.FindWindowById(labelId)
  541. ctype = self.FindWindowById(ctypeId)
  542. value = self.FindWindowById(valueId)
  543. dataSizer.Add(label, proportion = 0,
  544. flag = wx.ALIGN_CENTER_VERTICAL)
  545. dataSizer.Add(ctype, proportion = 0,
  546. flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
  547. dataSizer.Add(value, proportion = 0,
  548. flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  549. self.dataPanel.SetAutoLayout(True)
  550. self.dataPanel.SetSizer(dataSizer)
  551. dataSizer.Fit(self.dataPanel)
  552. if self.usebox:
  553. self.boxSizer.Add(item = self.dataPanel, proportion = 1,
  554. flag = wx.EXPAND | wx.ALL, border = 5)
  555. # buttons
  556. btnSizer = wx.StdDialogButtonSizer()
  557. btnSizer.AddButton(self.btnCancel)
  558. btnSizer.AddButton(self.btnSubmit)
  559. btnSizer.Realize()
  560. if not self.usebox:
  561. sizer.Add(item = self.dataPanel, proportion = 1,
  562. flag = wx.EXPAND | wx.ALL, border = 5)
  563. else:
  564. sizer.Add(item = self.boxSizer, proportion = 1,
  565. flag = wx.EXPAND | wx.ALL, border = 5)
  566. sizer.Add(item = btnSizer, proportion = 0,
  567. flag = wx.EXPAND | wx.ALL, border = 5)
  568. framewidth = self.GetBestSize()[0] + 25
  569. self.SetMinSize((framewidth, 250))
  570. self.SetAutoLayout(True)
  571. self.SetSizer(sizer)
  572. sizer.Fit(self)
  573. self.Layout()
  574. def GetValues(self, columns = None):
  575. """!Return list of values (casted to string).
  576. If columns is given (list), return only values of given columns.
  577. """
  578. valueList = list()
  579. for labelId, ctypeId, valueId in self.widgets:
  580. column = self.FindWindowById(labelId).GetLabel()
  581. if columns is None or column in columns:
  582. value = GetUnicodeValue(self.FindWindowById(valueId).GetValue())
  583. valueList.append(value)
  584. # add key value
  585. if self.usebox:
  586. valueList.insert(self.keyId, GetUnicodeValue(str(self.cat)))
  587. return valueList
  588. class AddColumnDialog(wx.Dialog):
  589. def __init__(self, parent, title, id = wx.ID_ANY,
  590. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  591. """!Dialog for adding column into table
  592. """
  593. wx.Dialog.__init__(self, parent, id, title, style = style)
  594. self.CenterOnParent()
  595. self.data = {}
  596. self.data['addColName'] = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = '',
  597. size = (150, -1), style = wx.TE_PROCESS_ENTER)
  598. self.data['addColType'] = wx.Choice (parent = self, id = wx.ID_ANY,
  599. choices = ["integer",
  600. "double",
  601. "varchar",
  602. "date"]) # FIXME
  603. self.data['addColType'].SetSelection(0)
  604. self.data['addColType'].Bind(wx.EVT_CHOICE, self.OnTableChangeType)
  605. self.data['addColLength'] = wx.SpinCtrl(parent = self, id = wx.ID_ANY, size = (65, -1),
  606. initial = 250,
  607. min = 1, max = 1e6)
  608. self.data['addColLength'].Enable(False)
  609. # buttons
  610. self.btnCancel = wx.Button(self, wx.ID_CANCEL)
  611. self.btnOk = wx.Button(self, wx.ID_OK)
  612. self.btnOk.SetDefault()
  613. self._layout()
  614. def _layout(self):
  615. sizer = wx.BoxSizer(wx.VERTICAL)
  616. addSizer = wx.BoxSizer(wx.HORIZONTAL)
  617. addSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Column")),
  618. flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  619. border = 5)
  620. addSizer.Add(item = self.data['addColName'], proportion = 1,
  621. flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  622. border = 5)
  623. addSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Type")),
  624. flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  625. border = 5)
  626. addSizer.Add(item = self.data['addColType'],
  627. flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  628. border = 5)
  629. addSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Length")),
  630. flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  631. border = 5)
  632. addSizer.Add(item = self.data['addColLength'],
  633. flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  634. border = 5)
  635. sizer.Add(item = addSizer, proportion = 0,
  636. flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  637. btnSizer = wx.StdDialogButtonSizer()
  638. btnSizer.AddButton(self.btnCancel)
  639. btnSizer.AddButton(self.btnOk)
  640. btnSizer.Realize()
  641. sizer.Add(item = btnSizer, proportion = 0,
  642. flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
  643. self.SetSizer(sizer)
  644. self.Fit()
  645. def GetData(self):
  646. """!Get inserted data from dialog's widgets"""
  647. values = {}
  648. values['name'] = self.data['addColName'].GetValue()
  649. values['ctype'] = self.data['addColType'].GetStringSelection()
  650. values['length'] = int(self.data['addColLength'].GetValue())
  651. return values
  652. def OnTableChangeType(self, event):
  653. """!Data type for new column changed. Enable or disable
  654. data length widget"""
  655. if event.GetString() == "varchar":
  656. self.data['addColLength'].Enable(True)
  657. else:
  658. self.data['addColLength'].Enable(False)