dialogs.py 31 KB

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