dbm.py 138 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440
  1. """
  2. @package dbm.py
  3. @brief GRASS Attribute Table Manager
  4. This program is based on FileHunter, published in 'The wxPython Linux
  5. Tutorial' on wxPython WIKI pages.
  6. It also uses some functions at
  7. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/426407
  8. @code
  9. python dbm.py vector@mapset
  10. @endcode
  11. List of classes:
  12. - Log
  13. - VirtualAttributeList
  14. - AttributeManager
  15. - DisplayAttributesDialog
  16. - VectorDBInfo
  17. - ModifyTableRecord
  18. (C) 2007-2008 by the GRASS Development Team
  19. This program is free software under the GNU General Public
  20. License (>=v2). Read the file COPYING that comes with GRASS
  21. for details.
  22. @author Jachym Cepicky <jachym.cepicky gmail.com>
  23. @author Martin Landa <landa.martin gmail.com>
  24. """
  25. import sys
  26. import os
  27. import locale
  28. import tempfile
  29. import copy
  30. ### i18N
  31. import gettext
  32. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  33. import globalvar
  34. globalvar.CheckForWx()
  35. import wx
  36. import wx.lib.mixins.listctrl as listmix
  37. import wx.lib.flatnotebook as FN
  38. import wx.lib.scrolledpanel as scrolled
  39. import sqlbuilder
  40. import grassenv
  41. import gcmd
  42. import utils
  43. import gdialogs
  44. from debug import Debug as Debug
  45. from preferences import globalSettings as UserSettings
  46. class Log:
  47. """
  48. The log output is redirected to the status bar of the containing frame.
  49. """
  50. def __init__(self, parent):
  51. self.parent = parent
  52. def write(self, text_string):
  53. """Update status bar"""
  54. self.parent.SetStatusText(text_string.strip())
  55. class VirtualAttributeList(wx.ListCtrl,
  56. listmix.ListCtrlAutoWidthMixin,
  57. listmix.ColumnSorterMixin):
  58. """
  59. Support virtual list class
  60. """
  61. def __init__(self, parent, log, mapDBInfo, layer):
  62. wx.ListCtrl.__init__(self, parent=parent, id=wx.ID_ANY,
  63. style=wx.LC_REPORT | wx.LC_HRULES |
  64. wx.LC_VRULES | wx.LC_VIRTUAL | wx.LC_SORT_ASCENDING)
  65. #
  66. # initialize variables
  67. #
  68. self.log = log
  69. self.mapDBInfo = mapDBInfo
  70. self.layer = layer
  71. self.columns = {} # <- LoadData()
  72. # self.selectedCats = []
  73. # self.lastTurnSelectedCats = [] # just temporary, for comparation
  74. #
  75. # add some attributes (colourful background for each item rows)
  76. #
  77. self.attr1 = wx.ListItemAttr()
  78. # self.attr1.SetBackgroundColour("light blue")
  79. self.attr1.SetBackgroundColour(wx.Colour(238,238,238))
  80. self.attr2 = wx.ListItemAttr()
  81. self.attr2.SetBackgroundColour("white")
  82. self.il = wx.ImageList(16, 16)
  83. self.sm_up = self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_GO_UP, wx.ART_TOOLBAR,
  84. (16,16)))
  85. self.sm_dn = self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_GO_DOWN, wx.ART_TOOLBAR,
  86. (16,16)))
  87. self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
  88. keyColumn = self.LoadData(layer)
  89. # setup mixins
  90. listmix.ListCtrlAutoWidthMixin.__init__(self)
  91. listmix.ColumnSorterMixin.__init__(self, len(self.columns))
  92. # sort item by category (id)
  93. if keyColumn > -1:
  94. self.SortListItems(col=keyColumn, ascending=True)
  95. else:
  96. self.SortListItems(col=0, ascending=True)
  97. # events
  98. self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
  99. self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
  100. self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColumnClick) # sorting
  101. # self.Bind(wx.EVT_LIST_DELETE_ITEM, self.OnItemDelete, self.list)
  102. # self.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self.OnColRightClick, self.list)
  103. # self.Bind(wx.EVT_LIST_COL_BEGIN_DRAG, self.OnColBeginDrag, self.list)
  104. # self.Bind(wx.EVT_LIST_COL_DRAGGING, self.OnColDragging, self.list)
  105. # self.Bind(wx.EVT_LIST_COL_END_DRAG, self.OnColEndDrag, self.list)
  106. # self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit, self.list)
  107. # self.list.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
  108. # self.list.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
  109. def Update(self, mapDBInfo):
  110. """Update list according new mapDBInfo description"""
  111. self.mapDBInfo = mapDBInfo
  112. self.LoadData(self.layer)
  113. def LoadData(self, layer, sql=None):
  114. """Load data into list
  115. @param layer layer number
  116. @param sql SQL select statement (if None 'SELECT * FROM table)
  117. @return id of key column
  118. @return -1 if key column is not displayed
  119. """
  120. self.log.write(_("Loading data..."))
  121. # These two should probably be passed to init more cleanly
  122. # setting the numbers of items = number of elements in the dictionary
  123. self.itemDataMap = {}
  124. self.itemIndexMap = []
  125. self.itemCatsMap = {}
  126. self.DeleteAllItems()
  127. # self.ClearAll()
  128. for i in range(self.GetColumnCount()):
  129. self.DeleteColumn(0)
  130. tableName = self.mapDBInfo.layers[layer]['table']
  131. keyColumn = self.mapDBInfo.layers[layer]['key']
  132. self.columns = self.mapDBInfo.tables[tableName]
  133. if sql is None:
  134. sql = "SELECT * FROM %s" % tableName
  135. if sql[7] != '*':
  136. columnNames = sql[7:].split(' ')[0].split(',')
  137. else:
  138. columnNames = self.mapDBInfo.GetColumns(tableName)
  139. try:
  140. # for maps connected via v.external
  141. keyId = columnNames.index(keyColumn)
  142. except:
  143. keyId = -1
  144. i = 0
  145. info = wx.ListItem()
  146. info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
  147. info.m_image = -1
  148. info.m_format = 0
  149. for column in columnNames:
  150. info.m_text = column
  151. self.InsertColumnInfo(i, info)
  152. i += 1
  153. if i >= 256:
  154. self.log.write(_("Can display only 256 columns."))
  155. #
  156. # read data
  157. #
  158. # FIXME: Max. number of rows, while the GUI is still usable
  159. # stdout can be very large, do not use PIPE, redirect to temp file
  160. # TODO: more effective way should be implemented...
  161. outFile = tempfile.NamedTemporaryFile(mode='w+b')
  162. selectCommand = gcmd.Command(["db.select", "-c", "--q",
  163. "sql=%s" % sql,
  164. "database=%s" % self.mapDBInfo.layers[layer]["database"],
  165. "driver=%s" % self.mapDBInfo.layers[layer]["driver"],
  166. "fs=|"],
  167. stdout=outFile)
  168. i = 0
  169. outFile.seek(0)
  170. while True:
  171. # os.linesep doesn't work here (MSYS)
  172. record = outFile.readline().replace('\n', '')
  173. if not record:
  174. break
  175. self.itemDataMap[i] = []
  176. j = 0
  177. for value in record.split('|'):
  178. # casting ...
  179. try:
  180. self.itemDataMap[i].append(self.columns[columnNames[j]]['ctype'] (value))
  181. except:
  182. self.itemDataMap[i].append('')
  183. if keyId > -1 and keyId == j:
  184. try:
  185. cat = self.columns[columnNames[j]]['ctype'] (value)
  186. except ValueError, e:
  187. cat = -1
  188. wx.MessageBox(parent=self,
  189. message=_("Error loading attribute data. "
  190. "Record number: %(rec)d. Unable to cast value '%(val)s' in "
  191. "key column (%(key)s) to integer.\n\n"
  192. "Details: %(detail)s") % \
  193. { 'rec' : i + 1, 'val' : value,
  194. 'key' : keyColumn, 'detail' : e},
  195. caption=_("Error"),
  196. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  197. j += 1
  198. # insert to table
  199. # index = self.InsertStringItem(index=sys.maxint, label=str(self.itemDataMap[i][0]))
  200. # for j in range(len(self.itemDataMap[i][1:])):
  201. # self.SetStringItem(index=index, col=j+1, label=str(self.itemDataMap[i][j+1]))
  202. # self.SetItemData(item=index, data=i)
  203. self.itemIndexMap.append(i)
  204. if keyId > -1: # load cats only when LoadData() is called first time
  205. self.itemCatsMap[i] = cat
  206. i += 1
  207. if i >= 100000:
  208. self.log.write(_("Limit 100000 records."))
  209. break
  210. self.SetItemCount(i)
  211. i = 0
  212. for col in columnNames:
  213. width = self.columns[col]['length'] * 6 # FIXME
  214. if width < 60:
  215. width = 60
  216. if width > 300:
  217. width = 300
  218. self.SetColumnWidth(col=i, width=width)
  219. i += 1
  220. self.SendSizeEvent()
  221. return keyId
  222. def OnItemSelected(self, event):
  223. """Item selected. Add item to selected cats..."""
  224. # cat = int(self.GetItemText(event.m_itemIndex))
  225. # if cat not in self.selectedCats:
  226. # self.selectedCats.append(cat)
  227. # self.selectedCats.sort()
  228. event.Skip()
  229. def OnItemDeselected(self, event):
  230. """Item deselected. Remove item from selected cats..."""
  231. # cat = int(self.GetItemText(event.m_itemIndex))
  232. # if cat in self.selectedCats:
  233. # self.selectedCats.remove(cat)
  234. # self.selectedCats.sort()
  235. event.Skip()
  236. def GetSelectedItems(self):
  237. """Return list of selected items (category numbers)"""
  238. cats = []
  239. item = self.GetFirstSelected()
  240. while item != -1:
  241. cats.append(self.GetItemText(item))
  242. item = self.GetNextSelected(item)
  243. return cats
  244. def GetColumnText(self, index, col):
  245. """Return column text"""
  246. item = self.GetItem(index, col)
  247. return item.GetText()
  248. def GetListCtrl(self):
  249. """Returt list"""
  250. return self
  251. def OnGetItemText(self, item, col):
  252. """Get item text"""
  253. index = self.itemIndexMap[item]
  254. s = str(self.itemDataMap[index][col])
  255. return s
  256. def OnGetItemAttr(self, item):
  257. """Get item attributes"""
  258. index = self.itemIndexMap[item]
  259. if ( index % 2) == 0:
  260. return self.attr2
  261. else:
  262. return self.attr1
  263. def OnColumnClick(self, event):
  264. """Column heading clicked -> sorting"""
  265. self._col = event.GetColumn()
  266. # remove duplicated arrow symbol from column header
  267. # FIXME: should be done automatically
  268. info = wx.ListItem()
  269. info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE
  270. info.m_image = -1
  271. for column in range(self.GetColumnCount()):
  272. info.m_text = self.GetColumn(column).GetText()
  273. self.SetColumn(column, info)
  274. event.Skip()
  275. def SortItems(self, sorter=cmp):
  276. """Sort items"""
  277. items = list(self.itemDataMap.keys())
  278. items.sort(self.Sorter)
  279. self.itemIndexMap = items
  280. # redraw the list
  281. self.Refresh()
  282. def Sorter(self, key1, key2):
  283. colName = self.GetColumn(self._col).GetText()
  284. ascending = self._colSortFlag[self._col]
  285. try:
  286. item1 = self.columns[colName]["ctype"](self.itemDataMap[key1][self._col])
  287. item2 = self.columns[colName]["ctype"](self.itemDataMap[key2][self._col])
  288. except ValueError:
  289. item1 = self.itemDataMap[key1][self._col]
  290. item2 = self.itemDataMap[key2][self._col]
  291. if type(item1) == type('') or type(item2) == type(''):
  292. cmpVal = locale.strcoll(str(item1), str(item2))
  293. else:
  294. cmpVal = cmp(item1, item2)
  295. # If the items are equal then pick something else to make the sort value unique
  296. if cmpVal == 0:
  297. cmpVal = apply(cmp, self.GetSecondarySortValues(self._col, key1, key2))
  298. if ascending:
  299. return cmpVal
  300. else:
  301. return -cmpVal
  302. def GetSortImages(self):
  303. """Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py"""
  304. return (self.sm_dn, self.sm_up)
  305. class AttributeManager(wx.Frame):
  306. """
  307. GRASS Attribute manager main window
  308. """
  309. def __init__(self, parent, id, title, vectmap,
  310. size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE,
  311. pointdata=None):
  312. self.vectmap = vectmap
  313. self.pointdata = pointdata
  314. self.parent = parent # GMFrame
  315. wx.Frame.__init__(self, parent, id, title, style=style)
  316. # icon
  317. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
  318. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  319. try:
  320. self.map = self.parent.curr_page.maptree.Map
  321. self.mapdisplay = self.parent.curr_page.maptree.mapdisplay
  322. except:
  323. self.map = self.mapdisplay = None
  324. if pointdata:
  325. self.icon = pointdata[0]
  326. self.pointsize = pointdata[1]
  327. else:
  328. self.icon = None
  329. self.pointsize = None
  330. # status bar log class
  331. self.log = Log(self) # -> statusbar
  332. # query map layer (if parent (GMFrame) is given)
  333. self.qlayer = None
  334. # -> layers / tables description
  335. self.mapDBInfo = VectorDBInfo(self.vectmap)
  336. if len(self.mapDBInfo.layers.keys()) == 0:
  337. wx.MessageBox(parent=self.parent,
  338. message=_("Database connection for vector map <%s> "
  339. "is not defined in DB file. "
  340. "You can define new connection in "
  341. "'Manage layers' tab.") % self.vectmap,
  342. caption=_("Attribute Table Manager"),
  343. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  344. #
  345. # list of command/SQL statements to be performed
  346. #
  347. self.listOfCommands = []
  348. self.listOfSQLStatements = []
  349. self.CreateStatusBar(number=1)
  350. # set up virtual lists (each layer)
  351. ### {layer: list, widgets...}
  352. self.layerPage = {}
  353. # auinotebook (browse, manage, settings)
  354. #self.notebook = wx.aui.AuiNotebook(parent=self, id=wx.ID_ANY,
  355. # style=wx.aui.AUI_NB_BOTTOM)
  356. # really needed (ML)
  357. # self.notebook.SetFont(wx.Font(10, wx.FONTFAMILY_MODERN, wx.NORMAL, wx.NORMAL, 0, ''))
  358. self.notebook = FN.FlatNotebook(parent=self.panel, id=wx.ID_ANY,
  359. style=FN.FNB_BOTTOM |
  360. FN.FNB_NO_NAV_BUTTONS |
  361. FN.FNB_FANCY_TABS)
  362. dbmStyle = globalvar.FNPageStyle
  363. self.browsePage = FN.FlatNotebook(self.panel, id=wx.ID_ANY,
  364. style=dbmStyle)
  365. # self.notebook.AddPage(self.browsePage, caption=_("Browse data"))
  366. self.notebook.AddPage(self.browsePage, text=_("Browse data")) # FN
  367. self.browsePage.SetTabAreaColour(globalvar.FNPageColor)
  368. self.manageTablePage = FN.FlatNotebook(self.panel, id=wx.ID_ANY,
  369. style=dbmStyle)
  370. #self.notebook.AddPage(self.manageTablePage, caption=_("Manage tables"))
  371. self.notebook.AddPage(self.manageTablePage, text=_("Manage tables")) # FN
  372. self.manageTablePage.SetTabAreaColour(globalvar.FNPageColor)
  373. self.manageLayerPage = FN.FlatNotebook(self.panel, id=wx.ID_ANY,
  374. style=dbmStyle)
  375. #self.notebook.AddPage(self.manageLayerPage, caption=_("Manage layers"))
  376. self.notebook.AddPage(self.manageLayerPage, text=_("Manage layers")) # FN
  377. self.manageLayerPage.SetTabAreaColour(globalvar.FNPageColor)
  378. self.infoCollapseLabelExp = _("Click here to show database connection information")
  379. self.infoCollapseLabelCol = _("Click here to hide database connection information")
  380. self.__createBrowsePage()
  381. self.__createManageTablePage()
  382. self.__createManageLayerPage()
  383. self.notebook.SetSelection(0) # select browse tab
  384. #
  385. # buttons
  386. #
  387. self.btnQuit = wx.Button(parent=self.panel, id=wx.ID_EXIT)
  388. # events
  389. self.btnQuit.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
  390. self.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnLayerPageChanged, self.browsePage)
  391. self.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnLayerPageChanged, self.manageTablePage)
  392. # do layout
  393. self.__layout()
  394. # self.SetMinSize(self.GetBestSize())
  395. self.SetSize((680, 550)) # FIXME hard-coded size
  396. self.SetMinSize(self.GetSize())
  397. def __createBrowsePage(self, onlyLayer=-1):
  398. """Create browse tab page"""
  399. for layer in self.mapDBInfo.layers.keys():
  400. if onlyLayer > 0 and layer != onlyLayer:
  401. continue
  402. panel = wx.Panel(parent=self.browsePage, id=wx.ID_ANY)
  403. self.layerPage[layer] = {'browsePage': panel.GetId()}
  404. self.browsePage.AddPage(page=panel, text=" %d / %s %s" % \
  405. (layer, _("Table"), self.mapDBInfo.layers[layer]['table']))
  406. pageSizer = wx.BoxSizer(wx.VERTICAL)
  407. # attribute data
  408. listBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
  409. label=" %s " % _("Attribute data - right-click to edit/manage records"))
  410. listSizer = wx.StaticBoxSizer(listBox, wx.VERTICAL)
  411. sqlBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
  412. label=" %s " % _("SQL Query"))
  413. sqlSizer = wx.StaticBoxSizer(sqlBox, wx.VERTICAL)
  414. win = VirtualAttributeList(panel, self.log,
  415. self.mapDBInfo, layer)
  416. win.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnDataItemActivated)
  417. win.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnDataRightUp) #wxMSW
  418. win.Bind(wx.EVT_RIGHT_UP, self.OnDataRightUp) #wxGTK
  419. if UserSettings.Get(group='atm', key='leftDbClick', subkey='selection') == 0:
  420. win.Bind(wx.EVT_LEFT_DCLICK, self.OnDataItemEdit)
  421. win.Bind(wx.EVT_COMMAND_LEFT_DCLICK, self.OnDataItemEdit)
  422. else:
  423. win.Bind(wx.EVT_LEFT_DCLICK, self.OnDataDrawSelected)
  424. win.Bind(wx.EVT_COMMAND_LEFT_DCLICK, self.OnDataDrawSelected)
  425. listSizer.Add(item=win, proportion=1,
  426. flag=wx.EXPAND | wx.ALL,
  427. border=3)
  428. # sql statement box
  429. btnApply = wx.Button(parent=panel, id=wx.ID_APPLY)
  430. btnApply.SetToolTipString(_("Apply SELECT statement and reload data records"))
  431. btnApply.Bind(wx.EVT_BUTTON, self.OnApplySqlStatement)
  432. btnSqlBuilder = wx.Button(parent=panel, id=wx.ID_ANY, label=_("SQL Builder"))
  433. btnSqlBuilder.Bind(wx.EVT_BUTTON, self.OnBuilder)
  434. sqlSimple = wx.RadioButton(parent=panel, id=wx.ID_ANY,
  435. label=_("Simple"))
  436. sqlSimple.SetValue(True)
  437. sqlAdvanced = wx.RadioButton(parent=panel, id=wx.ID_ANY,
  438. label=_("Advanced"))
  439. sqlSimple.Bind(wx.EVT_RADIOBUTTON, self.OnChangeSql)
  440. sqlAdvanced.Bind(wx.EVT_RADIOBUTTON, self.OnChangeSql)
  441. sqlWhere = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value="",
  442. style=wx.TE_PROCESS_ENTER)
  443. sqlStatement = wx.TextCtrl(parent=panel, id=wx.ID_ANY,
  444. value="SELECT * FROM %s" % \
  445. self.mapDBInfo.layers[layer]['table'],
  446. style=wx.TE_PROCESS_ENTER)
  447. sqlWhere.Bind(wx.EVT_TEXT_ENTER, self.OnApplySqlStatement)
  448. sqlStatement.Bind(wx.EVT_TEXT_ENTER, self.OnApplySqlStatement)
  449. sqlLabel = wx.StaticText(parent=panel, id=wx.ID_ANY,
  450. label="SELECT * FROM %s WHERE " % \
  451. self.mapDBInfo.layers[layer]['table'])
  452. label_query = wx.StaticText(parent=panel, id=wx.ID_ANY,
  453. label="")
  454. sqlFlexSizer = wx.FlexGridSizer (cols=3, hgap=5, vgap=5)
  455. sqlFlexSizer.AddGrowableCol(1)
  456. sqlFlexSizer.Add(item=sqlSimple,
  457. flag=wx.ALIGN_CENTER_VERTICAL)
  458. sqlSimpleSizer = wx.BoxSizer(wx.HORIZONTAL)
  459. sqlSimpleSizer.Add(item=sqlLabel,
  460. flag=wx.ALIGN_CENTER_VERTICAL)
  461. sqlSimpleSizer.Add(item=sqlWhere, proportion=1,
  462. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  463. sqlFlexSizer.Add(item=sqlSimpleSizer,
  464. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  465. sqlFlexSizer.Add(item=btnApply,
  466. flag=wx.ALIGN_RIGHT)
  467. sqlFlexSizer.Add(item=sqlAdvanced,
  468. flag=wx.ALIGN_CENTER_VERTICAL)
  469. sqlFlexSizer.Add(item=sqlStatement,
  470. flag=wx.EXPAND)
  471. sqlFlexSizer.Add(item=btnSqlBuilder,
  472. flag=wx.ALIGN_RIGHT)
  473. sqlSizer.Add(item=sqlFlexSizer,
  474. flag=wx.ALL | wx.EXPAND,
  475. border=3)
  476. pageSizer.Add(item=listSizer,
  477. proportion=1,
  478. flag=wx.ALL | wx.EXPAND,
  479. border=5)
  480. pageSizer.Add(item=sqlSizer,
  481. proportion=0,
  482. flag=wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.EXPAND,
  483. border=5)
  484. panel.SetSizer(pageSizer)
  485. self.layerPage[layer]['data'] = win.GetId()
  486. self.layerPage[layer]['simple'] = sqlSimple.GetId()
  487. self.layerPage[layer]['advanced'] = sqlAdvanced.GetId()
  488. self.layerPage[layer]['where'] = sqlWhere.GetId()
  489. self.layerPage[layer]['builder'] = btnSqlBuilder.GetId()
  490. self.layerPage[layer]['statement'] = sqlStatement.GetId()
  491. self.browsePage.SetSelection(0) # select first layer
  492. try:
  493. self.layer = self.mapDBInfo.layers.keys()[0]
  494. self.OnChangeSql(None)
  495. self.log.write(_("Number of loaded records: %d") % \
  496. self.FindWindowById(self.layerPage[self.layer]['data']).GetItemCount())
  497. except IndexError:
  498. self.layer = None
  499. def __createManageTablePage(self, onlyLayer=-1):
  500. """Create manage page (create/link and alter tables)"""
  501. for layer in self.mapDBInfo.layers.keys():
  502. if onlyLayer > 0 and layer != onlyLayer:
  503. continue
  504. panel = wx.Panel(parent=self.manageTablePage, id=wx.ID_ANY)
  505. self.layerPage[layer]['tablePage'] = panel.GetId()
  506. self.manageTablePage.AddPage(page=panel, text=" %d / %s %s" % (layer, _("Table"), self.mapDBInfo.layers[layer]['table']))
  507. pageSizer = wx.BoxSizer(wx.VERTICAL)
  508. #
  509. # dbInfo
  510. #
  511. infoCollapse = wx.CollapsiblePane(parent=panel,
  512. label=self.infoCollapseLabelExp,
  513. style=wx.CP_DEFAULT_STYLE |
  514. wx.CP_NO_TLW_RESIZE | wx.EXPAND)
  515. self.MakeInfoPaneContent(layer, infoCollapse.GetPane())
  516. infoCollapse.Collapse(False)
  517. self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnInfoPaneChanged, infoCollapse)
  518. #
  519. # table description
  520. #
  521. table = self.mapDBInfo.layers[layer]['table']
  522. tableBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
  523. label=" %s " % _("Table <%s> - right-click to delete column(s)") % table)
  524. tableSizer = wx.StaticBoxSizer(tableBox, wx.VERTICAL)
  525. list = self.__createTableDesc(panel, table)
  526. list.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnTableRightUp) #wxMSW
  527. list.Bind(wx.EVT_RIGHT_UP, self.OnTableRightUp) #wxGTK
  528. self.layerPage[layer]['tableData'] = list.GetId()
  529. #
  530. # add column
  531. #
  532. columnBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
  533. label=" %s " % _("Manage columns"))
  534. columnSizer = wx.StaticBoxSizer(columnBox, wx.VERTICAL)
  535. addSizer = wx.FlexGridSizer (cols=5, hgap=3, vgap=3)
  536. addSizer.AddGrowableCol(3)
  537. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Column name"))
  538. column = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value='',
  539. size=(150, -1), style=wx.TE_PROCESS_ENTER)
  540. column.Bind(wx.EVT_TEXT, self.OnTableAddColumnName)
  541. column.Bind(wx.EVT_TEXT_ENTER, self.OnTableItemAdd)
  542. self.layerPage[layer]['addColName'] = column.GetId()
  543. addSizer.Add(item=label,
  544. flag=wx.ALIGN_CENTER_VERTICAL)
  545. addSizer.Add(item=column,
  546. flag=wx.ALIGN_CENTER_VERTICAL)
  547. # data type
  548. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Data type"))
  549. addSizer.Add(item=label,
  550. flag=wx.ALIGN_CENTER_VERTICAL)
  551. subSizer = wx.BoxSizer(wx.HORIZONTAL)
  552. type = wx.Choice (parent=panel, id=wx.ID_ANY,
  553. choices = ["integer",
  554. "double",
  555. "varchar",
  556. "date"]) # FIXME
  557. type.SetSelection(0)
  558. type.Bind(wx.EVT_CHOICE, self.OnTableChangeType)
  559. self.layerPage[layer]['addColType'] = type.GetId()
  560. subSizer.Add(item=type,
  561. flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  562. border=3)
  563. # length
  564. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Data length"))
  565. length = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
  566. initial=250,
  567. min=1, max=1e6)
  568. length.Enable(False)
  569. self.layerPage[layer]['addColLength'] = length.GetId()
  570. subSizer.Add(item=label,
  571. flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  572. border=3)
  573. subSizer.Add(item=length,
  574. flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  575. border=3)
  576. addSizer.Add(item=subSizer,
  577. flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
  578. border=3)
  579. btnAddCol = wx.Button(parent=panel, id=wx.ID_ADD)
  580. btnAddCol.Bind(wx.EVT_BUTTON, self.OnTableItemAdd)
  581. btnAddCol.Enable(False)
  582. self.layerPage[layer]['addColButton'] = btnAddCol.GetId()
  583. addSizer.Add(item=btnAddCol,
  584. proportion=0,
  585. flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.FIXED_MINSIZE |
  586. wx.ALIGN_CENTER_VERTICAL )
  587. # rename col
  588. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Rename column"))
  589. column = wx.ComboBox(parent=panel, id=wx.ID_ANY, size=(150, -1),
  590. style=wx.CB_SIMPLE | wx.CB_READONLY,
  591. choices=self.mapDBInfo.GetColumns(table))
  592. column.SetSelection(0)
  593. self.layerPage[layer]['renameCol'] = column.GetId()
  594. addSizer.Add(item=label,
  595. flag=wx.ALIGN_CENTER_VERTICAL)
  596. addSizer.Add(item=column,
  597. flag=wx.ALIGN_CENTER_VERTICAL)
  598. label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("To"))
  599. columnTo = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value='',
  600. size=(150, -1), style=wx.TE_PROCESS_ENTER)
  601. columnTo.Bind(wx.EVT_TEXT, self.OnTableRenameColumnName)
  602. columnTo.Bind(wx.EVT_TEXT_ENTER, self.OnTableItemChange)
  603. self.layerPage[layer]['renameColTo'] = columnTo.GetId()
  604. addSizer.Add(item=label,
  605. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER)
  606. addSizer.Add(item=columnTo,
  607. flag=wx.ALIGN_CENTER_VERTICAL)
  608. btnRenameCol = wx.Button(parent=panel, id=wx.ID_ANY, label=_("&Rename"))
  609. btnRenameCol.Bind(wx.EVT_BUTTON, self.OnTableItemChange)
  610. btnRenameCol.Enable(False)
  611. self.layerPage[layer]['renameColButton'] = btnRenameCol.GetId()
  612. addSizer.Add(item=btnRenameCol,
  613. proportion=0,
  614. flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.FIXED_MINSIZE |
  615. wx.ALIGN_CENTER_VERTICAL)
  616. columnSizer.Add(item=addSizer, proportion=1,
  617. flag=wx.ALL | wx.EXPAND, border=3)
  618. tableSizer.Add(item=list,
  619. flag=wx.ALL | wx.EXPAND,
  620. proportion=1,
  621. border=3)
  622. pageSizer.Add(item=infoCollapse,
  623. flag=wx.ALL | wx.EXPAND,
  624. proportion=0,
  625. border=3)
  626. pageSizer.Add(item=tableSizer,
  627. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
  628. proportion=1,
  629. border=5)
  630. pageSizer.Add(item=columnSizer,
  631. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
  632. proportion=0,
  633. border=5)
  634. panel.SetSizer(pageSizer)
  635. self.layerPage[layer]['dbinfo'] = infoCollapse.GetId()
  636. self.manageTablePage.SetSelection(0) # select first layer
  637. try:
  638. self.layer = self.mapDBInfo.layers.keys()[0]
  639. except IndexError:
  640. self.layer = None
  641. def __createTableDesc(self, parent, table):
  642. """Create list with table description"""
  643. list = TableListCtrl(parent=parent, id=wx.ID_ANY,
  644. table=self.mapDBInfo.tables[table],
  645. columns=self.mapDBInfo.GetColumns(table))
  646. list.Populate()
  647. # sorter
  648. # itemDataMap = list.Populate()
  649. # listmix.ColumnSorterMixin.__init__(self, 2)
  650. return list
  651. def __createManageLayerPage(self):
  652. """Create manage page"""
  653. splitterWin = wx.SplitterWindow(parent=self.manageLayerPage, id=wx.ID_ANY)
  654. self.manageLayerPage.AddPage(page=splitterWin,
  655. text=_("Layers of vector map")) # dummy page
  656. #
  657. # list of layers
  658. #
  659. panelList = wx.Panel(parent=splitterWin, id=wx.ID_ANY)
  660. panelListSizer = wx.BoxSizer(wx.VERTICAL)
  661. layerBox = wx.StaticBox(parent=panelList, id=wx.ID_ANY,
  662. label=" %s " % _("List of layers"))
  663. layerSizer = wx.StaticBoxSizer(layerBox, wx.VERTICAL)
  664. self.layerList = self.__createLayerDesc(panelList)
  665. self.layerList.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnLayerRightUp) #wxMSW
  666. self.layerList.Bind(wx.EVT_RIGHT_UP, self.OnLayerRightUp) #wxGTK
  667. layerSizer.Add(item=self.layerList,
  668. flag=wx.ALL | wx.EXPAND,
  669. proportion=1,
  670. border=3)
  671. panelListSizer.Add(item=layerSizer,
  672. flag=wx.ALL | wx.EXPAND,
  673. proportion=1,
  674. border=3)
  675. panelList.SetSizer(panelListSizer)
  676. #
  677. # manage part
  678. #
  679. panelManage = wx.Panel(parent=splitterWin, id=wx.ID_ANY)
  680. manageSizer = wx.BoxSizer(wx.VERTICAL)
  681. self.manageLayerBook = LayerBook(parent=panelManage, id=wx.ID_ANY,
  682. parentDialog=self)
  683. manageSizer.Add(item=self.manageLayerBook,
  684. proportion=1,
  685. flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
  686. border=5)
  687. panelManage.SetSizer(manageSizer)
  688. #splitterWin.SetMinimumPaneSize(20)
  689. splitterWin.SplitHorizontally(panelList, panelManage, 100)
  690. def __createLayerDesc(self, parent):
  691. """Create list of linked layers"""
  692. list = LayerListCtrl(parent=parent, id=wx.ID_ANY,
  693. layers=self.mapDBInfo.layers)
  694. list.Populate()
  695. # sorter
  696. # itemDataMap = list.Populate()
  697. # listmix.ColumnSorterMixin.__init__(self, 2)
  698. return list
  699. def __layout(self):
  700. """Do layout"""
  701. # frame body
  702. mainSizer = wx.BoxSizer(wx.VERTICAL)
  703. # buttons
  704. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  705. btnSizer.Add(item=self.btnQuit, proportion=1,
  706. flag=wx.ALL | wx.ALIGN_RIGHT | wx.SHAPED, border=5)
  707. # btnSizer.Add(item=self.btnApply,
  708. # flag=wx.ALL, border=5)
  709. mainSizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND)
  710. mainSizer.Add(item=btnSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
  711. self.panel.SetAutoLayout(True)
  712. self.panel.SetSizer(mainSizer)
  713. mainSizer.Fit(self.panel)
  714. self.Layout()
  715. def OnDataRightUp(self, event):
  716. """Table description area, context menu"""
  717. if not hasattr(self, "popupDataID1"):
  718. self.popupDataID1 = wx.NewId()
  719. self.popupDataID2 = wx.NewId()
  720. self.popupDataID3 = wx.NewId()
  721. self.popupDataID4 = wx.NewId()
  722. self.popupDataID5 = wx.NewId()
  723. self.popupDataID6 = wx.NewId()
  724. self.popupDataID7 = wx.NewId()
  725. self.popupDataID8 = wx.NewId()
  726. self.popupDataID9 = wx.NewId()
  727. self.Bind(wx.EVT_MENU, self.OnDataItemEdit, id=self.popupDataID1)
  728. self.Bind(wx.EVT_MENU, self.OnDataItemAdd, id=self.popupDataID2)
  729. self.Bind(wx.EVT_MENU, self.OnDataItemDelete, id=self.popupDataID3)
  730. self.Bind(wx.EVT_MENU, self.OnDataItemDeleteAll, id=self.popupDataID4)
  731. self.Bind(wx.EVT_MENU, self.OnDataSelectAll, id=self.popupDataID5)
  732. self.Bind(wx.EVT_MENU, self.OnDataSelectNone, id=self.popupDataID6)
  733. self.Bind(wx.EVT_MENU, self.OnDataDrawSelected, id=self.popupDataID7)
  734. self.Bind(wx.EVT_MENU, self.OnExtractSelected, id=self.popupDataID8)
  735. self.Bind(wx.EVT_MENU, self.OnDataReload, id=self.popupDataID9)
  736. list = self.FindWindowById(self.layerPage[self.layer]['data'])
  737. # generate popup-menu
  738. menu = wx.Menu()
  739. menu.Append(self.popupDataID1, _("Edit selected record"))
  740. selected = list.GetFirstSelected()
  741. if selected == -1 or list.GetNextSelected(selected) != -1:
  742. menu.Enable(self.popupDataID1, False)
  743. menu.Append(self.popupDataID2, _("Insert new record"))
  744. menu.Append(self.popupDataID3, _("Delete selected record(s)"))
  745. menu.Append(self.popupDataID4, _("Delete all records"))
  746. menu.AppendSeparator()
  747. menu.Append(self.popupDataID5, _("Select all"))
  748. menu.Append(self.popupDataID6, _("Deselect all"))
  749. menu.AppendSeparator()
  750. menu.Append(self.popupDataID7, _("Display selected"))
  751. if not self.map or len(list.GetSelectedItems()) == 0:
  752. menu.Enable(self.popupDataID7, False)
  753. menu.Append(self.popupDataID8, _("Extract selected"))
  754. if list.GetFirstSelected() == -1:
  755. menu.Enable(self.popupDataID3, False)
  756. menu.Enable(self.popupDataID8, False)
  757. menu.AppendSeparator()
  758. menu.Append(self.popupDataID9, _("Reload"))
  759. self.PopupMenu(menu)
  760. menu.Destroy()
  761. # update statusbar
  762. self.log.write(_("Number of loaded records: %d") % \
  763. list.GetItemCount())
  764. def OnDataItemDelete(self, event):
  765. """Delete selected item(s) from the list (layer/category pair)"""
  766. list = self.FindWindowById(self.layerPage[self.layer]['data'])
  767. item = list.GetFirstSelected()
  768. table = self.mapDBInfo.layers[self.layer]["table"]
  769. key = self.mapDBInfo.layers[self.layer]["key"]
  770. indeces = []
  771. # collect SQL statements
  772. while item != -1:
  773. index = list.itemIndexMap[item]
  774. indeces.append(index)
  775. cat = list.itemCatsMap[index]
  776. self.listOfSQLStatements.append('DELETE FROM %s WHERE %s=%d' % \
  777. (table, key, cat))
  778. item = list.GetNextSelected(item)
  779. if UserSettings.Get(group='atm', key='askOnDeleteRec', subkey='enabled'):
  780. deleteDialog = wx.MessageBox(parent=self,
  781. message=_("Selected data records (%d) will permanently deleted "
  782. "from table. Do you want to delete them?") % \
  783. (len(self.listOfSQLStatements)),
  784. caption=_("Delete records"),
  785. style=wx.YES_NO | wx.CENTRE)
  786. if deleteDialog != wx.YES:
  787. self.listOfSQLStatements = []
  788. return
  789. # restore maps
  790. i = 0
  791. indexTemp = copy.copy(list.itemIndexMap)
  792. list.itemIndexMap = []
  793. dataTemp = copy.deepcopy(list.itemDataMap)
  794. list.itemDataMap = {}
  795. catsTemp = copy.deepcopy(list.itemCatsMap)
  796. list.itemCatsMap = {}
  797. i = 0
  798. for index in indexTemp:
  799. if index in indeces:
  800. continue
  801. list.itemIndexMap.append(i)
  802. list.itemDataMap[i] = dataTemp[index]
  803. list.itemCatsMap[i] = catsTemp[index]
  804. i += 1
  805. list.SetItemCount(len(list.itemIndexMap))
  806. # deselect items
  807. item = list.GetFirstSelected()
  808. while item != -1:
  809. list.SetItemState(item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
  810. item = list.GetNextSelected(item)
  811. # submit SQL statements
  812. self.ApplyCommands()
  813. event.Skip()
  814. def OnDataItemDeleteAll(self, event):
  815. """Delete all items from the list"""
  816. list = self.FindWindowById(self.layerPage[self.layer]['data'])
  817. if UserSettings.Get(group='atm', key='askOnDeleteRec', subkey='enabled'):
  818. deleteDialog = wx.MessageBox(parent=self,
  819. message=_("All data records (%d) will permanently deleted "
  820. "from table. Do you want to delete them?") % \
  821. (len(list.itemIndexMap)),
  822. caption=_("Delete records"),
  823. style=wx.YES_NO | wx.CENTRE)
  824. if deleteDialog != wx.YES:
  825. return
  826. list.DeleteAllItems()
  827. list.itemDataMap = {}
  828. list.itemIndexMap = []
  829. list.SetItemCount(0)
  830. table = self.mapDBInfo.layers[self.layer]["table"]
  831. self.listOfSQLStatements.append('DELETE FROM %s' % table)
  832. self.ApplyCommands()
  833. event.Skip()
  834. def OnDataDrawSelected(self, event):
  835. """Reload table description"""
  836. if self.map and self.mapdisplay:
  837. # add map layer with higlighted vector features
  838. self.AddQueryMapLayer()
  839. self.mapdisplay.MapWindow.UpdateMap(render=False, renderVector=False)
  840. event.Skip()
  841. def OnDataItemAdd(self, event):
  842. """Add new record to the attribute table"""
  843. list = self.FindWindowById(self.layerPage[self.layer]['data'])
  844. table = self.mapDBInfo.layers[self.layer]['table']
  845. keyColumn = self.mapDBInfo.layers[self.layer]['key']
  846. # (column name, value)
  847. data = []
  848. # collect names of all visible columns
  849. columnName = []
  850. for i in range(list.GetColumnCount()):
  851. columnName.append(list.GetColumn(i).GetText())
  852. # maximal category number
  853. maxCat = max(list.itemCatsMap.values())
  854. # key column must be always presented
  855. if keyColumn not in columnName:
  856. columnName.insert(0, keyColumn) # insert key column on first position
  857. data.append((keyColumn, str(maxCat + 1)))
  858. missingKey = True
  859. else:
  860. missingKey = False
  861. # add other visible columns
  862. colIdx = 0
  863. keyId = -1
  864. for col in columnName:
  865. if col == keyColumn: # key
  866. if missingKey is False:
  867. data.append((col, str(maxCat + 1)))
  868. keyId = colIdx
  869. else:
  870. data.append((col, ''))
  871. colIdx += 1
  872. dlg = ModifyTableRecord(parent=self, id=wx.ID_ANY,
  873. title=_("Insert new record"),
  874. data=data, keyEditable=(keyId, True))
  875. if dlg.ShowModal() == wx.ID_OK:
  876. try: # get category number
  877. cat = int(dlg.GetValues(columns=[keyColumn])[0])
  878. except:
  879. cat = -1
  880. try:
  881. if cat in list.itemCatsMap.values():
  882. raise ValueError(_("Record with category number %d "
  883. "already exists in the table.") % cat)
  884. values = dlg.GetValues() # values (need to be casted)
  885. columnsString = ''
  886. valuesString = ''
  887. for i in range(len(values)):
  888. if len(values[i]) == 0: # NULL
  889. if columnName[i] == keyColumn:
  890. raise ValueError(_("Category number (column %s)"
  891. " is missing.") % keyColumn)
  892. else:
  893. continue
  894. try:
  895. values[i] = list.columns[columnName[i]]['ctype'] (values[i])
  896. except:
  897. raise ValueError(_("Casting value '%(value)s' to %(type)s failed.") %
  898. {'value' : str(values[i]),
  899. 'type' : list.columns[columnName[i]]['type']})
  900. columnsString += '%s,' % columnName[i]
  901. if list.columns[columnName[i]]['ctype'] == str:
  902. valuesString += "'%s'," % values[i]
  903. else:
  904. valuesString += "%s," % values[i]
  905. except ValueError, err:
  906. wx.MessageBox(parent=self,
  907. message="%s%s%s" % (_("Unable to insert new record."),
  908. os.linesep, err),
  909. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  910. return
  911. # remove category if need
  912. if missingKey is True:
  913. del values[0]
  914. # add new item to the list
  915. index = max(list.itemIndexMap) + 1
  916. list.itemIndexMap.append(index)
  917. list.itemDataMap[index] = values
  918. list.itemCatsMap[index] = cat
  919. list.SetItemCount(list.GetItemCount() + 1)
  920. self.listOfSQLStatements.append('INSERT INTO %s (%s) VALUES(%s)' % \
  921. (table,
  922. columnsString.strip(','),
  923. valuesString.strip(',')))
  924. self.ApplyCommands()
  925. def OnDataItemEdit(self, event):
  926. """Edit selected record of the attribute table"""
  927. list = self.FindWindowById(self.layerPage[self.layer]['data'])
  928. item = list.GetFirstSelected()
  929. if item == -1:
  930. return
  931. table = self.mapDBInfo.layers[self.layer]['table']
  932. keyColumn = self.mapDBInfo.layers[self.layer]['key']
  933. cat = list.itemCatsMap[list.itemIndexMap[item]]
  934. # (column name, value)
  935. data = []
  936. # collect names of all visible columns
  937. columnName = []
  938. for i in range(list.GetColumnCount()):
  939. columnName.append(list.GetColumn(i).GetText())
  940. # key column must be always presented
  941. if keyColumn not in columnName:
  942. columnName.insert(0, keyColumn) # insert key column on first position
  943. data.append((keyColumn, str(cat)))
  944. keyId = 0
  945. missingKey = True
  946. else:
  947. missingKey = False
  948. # add other visible columns
  949. for i in range(len(columnName)):
  950. if columnName[i] == keyColumn: # key
  951. if missingKey is False:
  952. data.append((columnName[i], str(cat)))
  953. keyId = i
  954. else:
  955. if missingKey is True:
  956. value = list.GetItem(item, i-1).GetText()
  957. else:
  958. value = list.GetItem(item, i).GetText()
  959. data.append((columnName[i], value))
  960. dlg = ModifyTableRecord(parent=self, id=wx.ID_ANY,
  961. title=_("Update existing record"),
  962. data=data, keyEditable=(keyId, False))
  963. if dlg.ShowModal() == wx.ID_OK:
  964. values = dlg.GetValues() # string
  965. updateString = ''
  966. try:
  967. for i in range(len(values)):
  968. if i == keyId: # skip key column
  969. continue
  970. if str(list.GetItem(item, i).GetText()) != str(values[i]):
  971. if len(values[i]) > 0:
  972. try:
  973. if missingKey is True:
  974. idx = i - 1
  975. else:
  976. idx = i
  977. list.itemDataMap[item][idx] = \
  978. list.columns[columnName[i]]['ctype'] (values[i])
  979. except:
  980. raise ValueError(_("Casting value '%(value)s' to %(type)s failed.") % \
  981. {'value' : str(values[i]),
  982. 'type' : list.columns[columnName[i]]['type']})
  983. if list.columns[columnName[i]]['ctype'] == str:
  984. updateString += "%s='%s'," % (columnName[i], values[i])
  985. else:
  986. updateString += "%s=%s," % (columnName[i], values[i])
  987. else: # NULL
  988. updateString += "%s=NULL," % (columnName[i])
  989. except ValueError, err:
  990. wx.MessageBox(parent=self,
  991. message="%s%s%s" % (_("Unable to update existing record."),
  992. os.linesep, err),
  993. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  994. return
  995. if len(updateString) > 0:
  996. self.listOfSQLStatements.append('UPDATE %s SET %s WHERE %s=%d' % \
  997. (table, updateString.strip(','),
  998. keyColumn, cat))
  999. self.ApplyCommands()
  1000. def OnDataReload(self, event):
  1001. """Reload list of records"""
  1002. self.OnApplySqlStatement(None)
  1003. self.listOfSQLStatements = []
  1004. def OnDataSelectAll(self, event):
  1005. """Select all items"""
  1006. list = self.FindWindowById(self.layerPage[self.layer]['data'])
  1007. item = -1
  1008. while True:
  1009. item = list.GetNextItem(item)
  1010. if item == -1:
  1011. break
  1012. list.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
  1013. event.Skip()
  1014. def OnDataSelectNone(self, event):
  1015. """Deselect items"""
  1016. list = self.FindWindowById(self.layerPage[self.layer]['data'])
  1017. item = -1
  1018. while True:
  1019. item = list.GetNextItem(item, wx.LIST_STATE_SELECTED)
  1020. if item == -1:
  1021. break
  1022. list.SetItemState(item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
  1023. event.Skip()
  1024. def OnTableChangeType(self, event):
  1025. """Data type for new column changed. Enable or disable
  1026. data length widget"""
  1027. win = self.FindWindowById(self.layerPage[self.layer]['addColLength'])
  1028. if event.GetString() == "varchar":
  1029. win.Enable(True)
  1030. else:
  1031. win.Enable(False)
  1032. def OnTableRenameColumnName(self, event):
  1033. """Editing column name to be added to the table"""
  1034. btn = self.FindWindowById(self.layerPage[self.layer]['renameColButton'])
  1035. col = self.FindWindowById(self.layerPage[self.layer]['renameCol'])
  1036. colTo = self.FindWindowById(self.layerPage[self.layer]['renameColTo'])
  1037. if len(col.GetValue()) > 0 and len(colTo.GetValue()) > 0:
  1038. btn.Enable(True)
  1039. else:
  1040. btn.Enable(False)
  1041. event.Skip()
  1042. def OnTableAddColumnName(self, event):
  1043. """Editing column name to be added to the table"""
  1044. btn = self.FindWindowById(self.layerPage[self.layer]['addColButton'])
  1045. if len(event.GetString()) > 0:
  1046. btn.Enable(True)
  1047. else:
  1048. btn.Enable(False)
  1049. event.Skip()
  1050. def OnTableItemChange(self, event):
  1051. """Rename column in the table"""
  1052. list = self.FindWindowById(self.layerPage[self.layer]['tableData'])
  1053. name = self.FindWindowById(self.layerPage[self.layer]['renameCol']).GetValue()
  1054. nameTo = self.FindWindowById(self.layerPage[self.layer]['renameColTo']).GetValue()
  1055. table = self.mapDBInfo.layers[self.layer]["table"]
  1056. if not name or not nameTo:
  1057. wx.MessageBox(self=self,
  1058. message=_("Unable to rename column. "
  1059. "No column name defined."),
  1060. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1061. return
  1062. else:
  1063. item = list.FindItem(start=-1, str=name)
  1064. if item > -1:
  1065. if list.FindItem(start=-1, str=nameTo) > -1:
  1066. wx.MessageBox(parent=self,
  1067. message=_("Unable to rename column <%(column)s> to "
  1068. "<%(columnTo)s>. Column already exists "
  1069. "in the table <%(table)s>.") % \
  1070. {'column' : name, 'columnTo' : nameTo,
  1071. 'table' : table},
  1072. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1073. return
  1074. else:
  1075. list.SetItemText(item, nameTo)
  1076. self.listOfCommands.append(['v.db.renamecol',
  1077. 'map=%s' % self.vectmap,
  1078. 'layer=%d' % self.layer,
  1079. 'column=%s,%s' % (name, nameTo)])
  1080. else:
  1081. wx.MessageBox(parent=self,
  1082. message=_("Unable to rename column. "
  1083. "Column <%(column)s> doesn't exist in the table <%(table)s>.") %
  1084. {'column' : name, 'table' : table},
  1085. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1086. return
  1087. # apply changes
  1088. self.ApplyCommands()
  1089. # update widgets
  1090. self.FindWindowById(self.layerPage[self.layer]['renameCol']).SetItems(self.mapDBInfo.GetColumns(table))
  1091. self.FindWindowById(self.layerPage[self.layer]['renameCol']).SetSelection(0)
  1092. self.FindWindowById(self.layerPage[self.layer]['renameColTo']).SetValue('')
  1093. event.Skip()
  1094. def OnTableRightUp(self, event):
  1095. """Table description area, context menu"""
  1096. if not hasattr(self, "popupTableID"):
  1097. self.popupTableID1 = wx.NewId()
  1098. self.popupTableID2 = wx.NewId()
  1099. self.popupTableID3 = wx.NewId()
  1100. self.Bind(wx.EVT_MENU, self.OnTableItemDelete, id=self.popupTableID1)
  1101. self.Bind(wx.EVT_MENU, self.OnTableItemDeleteAll, id=self.popupTableID2)
  1102. self.Bind(wx.EVT_MENU, self.OnTableReload, id=self.popupTableID3)
  1103. # generate popup-menu
  1104. menu = wx.Menu()
  1105. menu.Append(self.popupTableID1, _("Drop selected column"))
  1106. if self.FindWindowById(self.layerPage[self.layer]['tableData']).GetFirstSelected() == -1:
  1107. menu.Enable(self.popupTableID1, False)
  1108. menu.Append(self.popupTableID2, _("Drop all columns"))
  1109. menu.AppendSeparator()
  1110. menu.Append(self.popupTableID3, _("Reload"))
  1111. self.PopupMenu(menu)
  1112. menu.Destroy()
  1113. def OnTableItemDelete(self, event):
  1114. """Delete selected item(s) from the list"""
  1115. list = self.FindWindowById(self.layerPage[self.layer]['tableData'])
  1116. item = list.GetFirstSelected()
  1117. while item != -1:
  1118. self.listOfCommands.append(['v.db.dropcol',
  1119. 'map=%s' % self.vectmap,
  1120. 'layer=%d' % self.layer,
  1121. 'column=%s' % list.GetItemText(item)])
  1122. list.DeleteItem(item)
  1123. item = list.GetFirstSelected()
  1124. # apply changes
  1125. self.ApplyCommands()
  1126. # update widgets
  1127. table = self.mapDBInfo.layers[self.layer]['table']
  1128. self.FindWindowById(self.layerPage[self.layer]['renameCol']).SetItems(self.mapDBInfo.GetColumns(table))
  1129. self.FindWindowById(self.layerPage[self.layer]['renameCol']).SetSelection(0)
  1130. event.Skip()
  1131. def OnTableItemDeleteAll(self, event):
  1132. """Delete all items from the list"""
  1133. table = self.mapDBInfo.layers[self.layer]['table']
  1134. cols = self.mapDBInfo.GetColumns(table)
  1135. for col in cols:
  1136. self.listOfCommands = [['v.db.dropcol',
  1137. 'map=%s' % self.vectmap,
  1138. 'layer=%d' % self.layer,
  1139. 'column=%s' % col]]
  1140. self.FindWindowById(self.layerPage[self.layer]['tableData']).DeleteAllItems()
  1141. # apply changes
  1142. self.ApplyCommands()
  1143. # update widgets
  1144. table = self.mapDBInfo.layers[self.layer]['table']
  1145. self.FindWindowById(self.layerPage[self.layer]['renameCol']).SetItems(self.mapDBInfo.GetColumns(table))
  1146. self.FindWindowById(self.layerPage[self.layer]['renameCol']).SetSelection(0)
  1147. event.Skip()
  1148. def OnTableReload(self, event=None):
  1149. """Reload table description"""
  1150. self.FindWindowById(self.layerPage[self.layer]['tableData']).Populate(update=True)
  1151. self.listOfCommands = []
  1152. def OnTableItemAdd(self, event):
  1153. """Add new column to the table"""
  1154. name = self.FindWindowById(self.layerPage[self.layer]['addColName']).GetValue()
  1155. if not name:
  1156. wx.MessageBox(parent=self,
  1157. message=_("Unable to add column to the table. "
  1158. "No column name defined."),
  1159. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1160. return
  1161. type = self.FindWindowById(self.layerPage[self.layer]['addColType']). \
  1162. GetStringSelection()
  1163. # cast type if needed
  1164. if type == 'double':
  1165. type = 'double precision'
  1166. if type == 'varchar':
  1167. length = int(self.FindWindowById(self.layerPage[self.layer]['addColLength']). \
  1168. GetValue())
  1169. else:
  1170. length = '' # FIXME
  1171. # add item to the list of table columns
  1172. list = self.FindWindowById(self.layerPage[self.layer]['tableData'])
  1173. # check for duplicate items
  1174. if list.FindItem(start=-1, str=name) > -1:
  1175. wx.MessageBox(parent=self,
  1176. message=_("Column <%(column)s> already exists in table <%(table)s>.") % \
  1177. {'column' : name, 'table' : self.mapDBInfo.layers[self.layer]["table"]},
  1178. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1179. return
  1180. index = list.InsertStringItem(sys.maxint, str(name))
  1181. list.SetStringItem(index, 0, str(name))
  1182. list.SetStringItem(index, 1, str(type))
  1183. list.SetStringItem(index, 2, str(length))
  1184. # add v.db.addcol command to the list
  1185. if type == 'varchar':
  1186. type += ' (%d)' % length
  1187. self.listOfCommands.append(['v.db.addcol',
  1188. 'map=%s' % self.vectmap,
  1189. 'layer=%d' % self.layer,
  1190. 'columns=%s %s' % (name, type)])
  1191. # apply changes
  1192. self.ApplyCommands()
  1193. # update widgets
  1194. self.FindWindowById(self.layerPage[self.layer]['addColName']).SetValue('')
  1195. def OnLayerPageChanged(self, event):
  1196. """Layer tab changed"""
  1197. pageNum = event.GetSelection()
  1198. self.layer = self.mapDBInfo.layers.keys()[pageNum]
  1199. try:
  1200. self.OnChangeSql(None)
  1201. # update statusbar
  1202. self.log.write(_("Number of loaded records: %d") % \
  1203. self.FindWindowById(self.layerPage[self.layer]['data']).\
  1204. GetItemCount())
  1205. except:
  1206. pass
  1207. def OnLayerRightUp(self, event):
  1208. """Layer description area, context menu"""
  1209. pass
  1210. def OnChangeSql(self, event):
  1211. """Switch simple/advanced sql statement"""
  1212. if self.FindWindowById(self.layerPage[self.layer]['simple']).GetValue():
  1213. self.FindWindowById(self.layerPage[self.layer]['where']).Enable(True)
  1214. self.FindWindowById(self.layerPage[self.layer]['statement']).Enable(False)
  1215. self.FindWindowById(self.layerPage[self.layer]['builder']).Enable(False)
  1216. else:
  1217. self.FindWindowById(self.layerPage[self.layer]['where']).Enable(False)
  1218. self.FindWindowById(self.layerPage[self.layer]['statement']).Enable(True)
  1219. self.FindWindowById(self.layerPage[self.layer]['builder']).Enable(True)
  1220. def ApplyCommands(self):
  1221. """Apply changes"""
  1222. # perform GRASS commands (e.g. v.db.addcol)
  1223. if len(self.listOfCommands) > 0:
  1224. for cmd in self.listOfCommands:
  1225. Debug.msg(3, 'AttributeManager.ApplyCommands() cmd=\'%s\'' %
  1226. ' '.join(cmd))
  1227. gcmd.Command(cmd)
  1228. self.mapDBInfo = VectorDBInfo(self.vectmap)
  1229. table = self.mapDBInfo.layers[self.layer]['table']
  1230. # update table description
  1231. list = self.FindWindowById(self.layerPage[self.layer]['tableData'])
  1232. list.Update(table=self.mapDBInfo.tables[table],
  1233. columns=self.mapDBInfo.GetColumns(table))
  1234. self.OnTableReload(None)
  1235. # update data list
  1236. list = self.FindWindowById(self.layerPage[self.layer]['data'])
  1237. list.Update(self.mapDBInfo)
  1238. # reset list of commands
  1239. self.listOfCommands = []
  1240. # perform SQL non-select statements (e.g. 'delete from table where cat=1')
  1241. if len(self.listOfSQLStatements) > 0:
  1242. sqlFile = tempfile.NamedTemporaryFile(mode="w")
  1243. for sql in self.listOfSQLStatements:
  1244. sqlFile.file.write(sql + ";\n")
  1245. sqlFile.file.flush()
  1246. driver = self.mapDBInfo.layers[self.layer]["driver"]
  1247. database = self.mapDBInfo.layers[self.layer]["database"]
  1248. cmd = ['db.execute',
  1249. 'input=%s' % sqlFile.name,
  1250. 'driver=%s' % driver,
  1251. 'database=%s' % database]
  1252. Debug.msg(3, 'AttributeManger.ApplyCommands(): %s' %
  1253. ';'.join(["%s" % s for s in self.listOfSQLStatements]))
  1254. gcmd.Command(cmd)
  1255. # reset list of statements
  1256. self.listOfSQLStatements = []
  1257. def OnApplySqlStatement(self, event):
  1258. """Apply simple/advanced sql statement"""
  1259. keyColumn = -1 # index of key column
  1260. listWin = self.FindWindowById(self.layerPage[self.layer]['data'])
  1261. if self.FindWindowById(self.layerPage[self.layer]['simple']).GetValue():
  1262. # simple sql statement
  1263. where = self.FindWindowById(self.layerPage[self.layer]['where']).GetValue().strip()
  1264. try:
  1265. if len(where) > 0:
  1266. sql = "SELECT * FROM %s WHERE %s" % (self.mapDBInfo.layers[self.layer]['table'],
  1267. where)
  1268. keyColumn = listWin.LoadData(self.layer, sql=sql)
  1269. else:
  1270. keyColumn = listWin.LoadData(self.layer)
  1271. except gcmd.CmdError:
  1272. wx.MessageBox(parent=self,
  1273. message=_("Loading attribute data failed. "
  1274. "Invalid SQL 'select' statement.\n\n"
  1275. "'%s'") % sql,
  1276. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1277. keyColumn = listWin.LoadData(self.layer)
  1278. self.FindWindowById(self.layerPage[self.layer]['where']).SetValue('')
  1279. else:
  1280. # advanced sql statement
  1281. # valid, cols, where = \
  1282. # self.ValidateSelectStatement( \
  1283. # self.FindWindowById(self.layerPage[self.layer]['statement']).GetValue().strip())
  1284. #
  1285. #Debug.msg(4, "AttributeManager.OnApplySqlStatament(): valid=%s, cols=%s, where=%s" %
  1286. # (valid, cols, where))
  1287. sql = self.FindWindowById(self.layerPage[self.layer]['statement']).GetValue()
  1288. try:
  1289. # if valid is True:
  1290. keyColumn = listWin.LoadData(self.layer,
  1291. sql=sql)
  1292. # else:
  1293. # raise gcmd.GException('')
  1294. except gcmd.CmdError:
  1295. wx.MessageBox(parent=self,
  1296. message=_("Loading attribute data failed. "
  1297. "Invalid SQL 'select' statement.\n\n"
  1298. "'%s'") % sql,
  1299. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1300. keyColumn = listWin.LoadData(self.layer)
  1301. self.FindWindowById(self.layerPage[self.layer]['statement']).\
  1302. SetValue("SELECT * FROM %s" % self.mapDBInfo.layers[self.layer]['table'])
  1303. # sort by key column
  1304. if keyColumn > -1:
  1305. listWin.SortListItems(col=keyColumn, ascending=True)
  1306. else:
  1307. listWin.SortListItems(col=0, ascending=True)
  1308. # update statusbar
  1309. self.log.write(_("Number of loaded records: %d") % \
  1310. self.FindWindowById(self.layerPage[self.layer]['data']).GetItemCount())
  1311. def ValidateSelectStatement(self, statement):
  1312. """Validate Select SQL statement
  1313. TODO: check list of columns and where statement
  1314. Return True if valid, False if not
  1315. Return list of columns (or '*' for all columns)
  1316. Return where statement
  1317. """
  1318. if statement[0:7].lower() != 'select ':
  1319. return (False, '', '')
  1320. cols = ''
  1321. index = 7
  1322. for c in statement[index:]:
  1323. if c == ' ':
  1324. break
  1325. cols += c
  1326. index += 1
  1327. tablelen = len(self.mapDBInfo.layers[self.layer]['table'])
  1328. if statement[index+1:index+6].lower() != 'from ' or \
  1329. statement[index+6:index+6+tablelen] != '%s' % \
  1330. (self.mapDBInfo.layers[self.layer]['table']):
  1331. return (False, '', '')
  1332. if len(statement[index+7+tablelen:]) > 0:
  1333. index = statement.lower().find('where ')
  1334. if index > -1:
  1335. where = statement[index+6:]
  1336. else:
  1337. where = ''
  1338. else:
  1339. where = ''
  1340. return (True, cols, where)
  1341. def OnInfoPaneChanged(self, event):
  1342. """Collapse database connection info box"""
  1343. if self.FindWindowById(self.layerPage[self.layer]['dbinfo']).IsExpanded():
  1344. self.FindWindowById(self.layerPage[self.layer]['dbinfo']).SetLabel( \
  1345. self.infoCollapseLabelCol)
  1346. else:
  1347. self.FindWindowById(self.layerPage[self.layer]['dbinfo']).SetLabel( \
  1348. self.infoCollapseLabelExp)
  1349. # redo layout
  1350. self.Layout()
  1351. def MakeInfoPaneContent(self, layer, pane):
  1352. """Create database connection information content"""
  1353. # connection info
  1354. border = wx.BoxSizer(wx.VERTICAL)
  1355. connectionInfoBox = wx.StaticBox(parent=pane, id=wx.ID_ANY,
  1356. label=" %s " % _("Database connection"))
  1357. infoSizer = wx.StaticBoxSizer(connectionInfoBox, wx.VERTICAL)
  1358. infoFlexSizer = wx.FlexGridSizer (cols=2, hgap=1, vgap=1)
  1359. infoFlexSizer.AddGrowableCol(1)
  1360. infoFlexSizer.Add(item=wx.StaticText(parent=pane, id=wx.ID_ANY,
  1361. label="Driver:"))
  1362. infoFlexSizer.Add(item=wx.StaticText(parent=pane, id=wx.ID_ANY,
  1363. label="%s" % \
  1364. self.mapDBInfo.layers[layer]['driver']))
  1365. infoFlexSizer.Add(item=wx.StaticText(parent=pane, id=wx.ID_ANY,
  1366. label="Database:"))
  1367. infoFlexSizer.Add(item=wx.StaticText(parent=pane, id=wx.ID_ANY,
  1368. label="%s" % \
  1369. self.mapDBInfo.layers[layer]['database']))
  1370. infoFlexSizer.Add(item=wx.StaticText(parent=pane, id=wx.ID_ANY,
  1371. label="Table:"))
  1372. infoFlexSizer.Add(item=wx.StaticText(parent=pane, id=wx.ID_ANY,
  1373. label="%s" % \
  1374. self.mapDBInfo.layers[layer]['table']))
  1375. infoFlexSizer.Add(item=wx.StaticText(parent=pane, id=wx.ID_ANY,
  1376. label="Key:"))
  1377. infoFlexSizer.Add(item=wx.StaticText(parent=pane, id=wx.ID_ANY,
  1378. label="%s" % \
  1379. self.mapDBInfo.layers[layer]['key']))
  1380. infoSizer.Add(item=infoFlexSizer,
  1381. proportion=1,
  1382. flag=wx.EXPAND | wx.ALL,
  1383. border=3)
  1384. border.Add(item=infoSizer,
  1385. proportion=1,
  1386. flag=wx.EXPAND | wx.ALL,
  1387. border=3)
  1388. pane.SetSizer(border)
  1389. def OnCloseWindow(self, event):
  1390. """Cancel button pressed"""
  1391. self.Close()
  1392. event.Skip()
  1393. def OnBuilder(self,event):
  1394. """SQL Builder button pressed"""
  1395. self.builder = sqlbuilder.SQLFrame(parent=self, id=wx.ID_ANY,
  1396. title=_("SQL Builder"),
  1397. vectmap=self.vectmap)
  1398. def OnTextEnter(self, event):
  1399. pass
  1400. def OnSQLBuilder(self, event):
  1401. pass
  1402. def OnDataItemActivated(self, event):
  1403. """Item activated, highlight selected item"""
  1404. self.OnDataDrawSelected(event)
  1405. event.Skip()
  1406. def OnExtractSelected(self, event):
  1407. """
  1408. Extract vector objects selected in attribute browse window
  1409. to new vector map
  1410. """
  1411. list = self.FindWindowById(self.layerPage[self.layer]['data'])
  1412. # cats = list.selectedCats[:]
  1413. cats = list.GetSelectedItems()
  1414. if len(cats) == 0:
  1415. wx.MessageBox(parent=self,
  1416. message=_('Nothing to extract.'),
  1417. caption=_('Extract selected'), style=wx.CENTRE)
  1418. return False
  1419. else:
  1420. # dialog to get file name
  1421. dlg = gdialogs.NewVectorDialog(parent=self, id=wx.ID_ANY, title=_('Extract selected'))
  1422. if dlg.ShowModal() == wx.ID_OK:
  1423. outmap, overwrite = dlg.GetName()
  1424. if outmap == '': # should not happen
  1425. return False
  1426. cmd = ["v.extract",
  1427. "input=%s" % self.vectmap,
  1428. "output=%s" % outmap,
  1429. "list=%s" % utils.ListOfCatsToRange(cats)]
  1430. if overwrite is True:
  1431. cmd.append('--overwrite')
  1432. p = gcmd.Command(cmd, stderr=None)
  1433. if p.returncode == 0:
  1434. return True
  1435. return False
  1436. def AddQueryMapLayer(self):
  1437. """Redraw a map
  1438. Return True if map has been redrawn, False if no map is given
  1439. """
  1440. list = self.FindWindowById(self.layerPage[self.layer]['data'])
  1441. cats = list.GetSelectedItems() # FIXME: category can be hiden in list
  1442. if self.mapdisplay.Map.GetLayerIndex(self.qlayer) < 0:
  1443. self.qlayer = None
  1444. if self.qlayer:
  1445. self.qlayer.SetCmd(self.mapdisplay.AddTmpVectorMapLayer(self.vectmap, cats, addLayer=False))
  1446. else:
  1447. self.qlayer = self.mapdisplay.AddTmpVectorMapLayer(self.vectmap, cats)
  1448. def UpdateDialog(self, layer):
  1449. """Updates dialog layout for given layer"""
  1450. #
  1451. # delete page
  1452. #
  1453. if layer in self.mapDBInfo.layers.keys():
  1454. # delete page
  1455. # draging pages disallowed
  1456. # if self.browsePage.GetPageText(page).replace('Layer ', '').strip() == str(layer):
  1457. # self.browsePage.DeletePage(page)
  1458. # break
  1459. self.browsePage.DeletePage(self.mapDBInfo.layers.keys().index(layer))
  1460. self.manageTablePage.DeletePage(self.mapDBInfo.layers.keys().index(layer))
  1461. # set current page selection
  1462. self.notebook.SetSelection(2)
  1463. # fetch fresh db info
  1464. self.mapDBInfo = VectorDBInfo(self.vectmap)
  1465. #
  1466. # add new page
  1467. #
  1468. if layer in self.mapDBInfo.layers.keys():
  1469. # 'browse data' page
  1470. self.__createBrowsePage(layer)
  1471. # 'manage tables' page
  1472. self.__createManageTablePage(layer)
  1473. # set current page selection
  1474. self.notebook.SetSelection(2)
  1475. #
  1476. # 'manage layers' page
  1477. #
  1478. # update list of layers
  1479. self.layerList.Update(self.mapDBInfo.layers)
  1480. self.layerList.Populate(update=True)
  1481. # update selected widgets
  1482. listOfLayers = map(str, self.mapDBInfo.layers.keys())
  1483. ### delete layer page
  1484. self.manageLayerBook.deleteLayer.SetItems(listOfLayers)
  1485. if len(listOfLayers) > 0:
  1486. self.manageLayerBook.deleteLayer.SetStringSelection(listOfLayers[0])
  1487. tableName = self.mapDBInfo.layers[int(listOfLayers[0])]['table']
  1488. maxLayer = max(self.mapDBInfo.layers.keys())
  1489. else:
  1490. tableName = ''
  1491. maxLayer = 0
  1492. self.manageLayerBook.deleteTable.SetLabel( \
  1493. _('Drop also linked attribute table (%s)') % \
  1494. tableName)
  1495. ### add layer page
  1496. self.manageLayerBook.addLayerWidgets['layer'][1].SetValue(\
  1497. maxLayer+1)
  1498. ### modify layer
  1499. self.manageLayerBook.modifyLayerWidgets['layer'][1].SetItems(listOfLayers)
  1500. self.manageLayerBook.OnChangeLayer(event=None)
  1501. # def OnMapClick(self, event):
  1502. # """
  1503. # Gets coordinates from mouse clicking on display window
  1504. # """
  1505. # Debug.msg(3, "VirtualAttributeList.OnMapClick()")
  1506. # # map coordinates
  1507. # x, y = self.mapdisp.MapWindow.Pixel2Cell(event.GetPositionTuple()[:])
  1508. # category = ""
  1509. # for line in os.popen("v.what east_north=%f,%f map=%s" %\
  1510. # (x,y,self.vectmap)).readlines():
  1511. # if "Category:" in line:
  1512. # category = line.strip().split(" ")[1]
  1513. # #print category
  1514. # for idx in range(self.GetItemCount()):
  1515. # item = self.GetItem(idx, 0)
  1516. # if item.GetText() == category:
  1517. # #print idx
  1518. # # self.Select(idx,True)
  1519. # self.EnsureVisible( idx )
  1520. # self.SetItemState(idx, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
  1521. # else:
  1522. # # self.SetItemState(idx, wx.LIST_STATE_DESELECTED, wx.LIST_STATE_DESELECTED)
  1523. # self.Select(idx,False)
  1524. # # try:
  1525. # # os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
  1526. # # cmd = "v.what -a east_north=%d,%d distance=%d map=%@%" % (x,y,100,self.tablename, self.self.mapset)
  1527. # # self.cmd_output.write(cmd+"\n----------\n")
  1528. # # p = Popen(cmd +" --verbose", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
  1529. # #
  1530. # # oline = p.stderr.readline()
  1531. # # while oline:
  1532. # # oline = oline.strip()
  1533. # # oline = p.stderr.readline()
  1534. # # if oline.find("GRASS_INFO_MESSAGE")>-1:
  1535. # # self.cmd_output.write(string.split(oline,maxsplit=1)[1]+"\n")
  1536. # # elif oline.find("GRASS_INFO_WARNING")>-1:
  1537. # # self.cmd_output.write("WARNING: "+string.split(oline,maxsplit=1)[1]+"\n")
  1538. # # elif oline.find("GRASS_INFO_ERROR")>-1:
  1539. # # self.cmd_output.write("ERROR: "+string.split(oline,maxsplit=1)[1]+"\n")
  1540. # #
  1541. # # oline = p.stdout.readline()
  1542. # # while oline:
  1543. # # oline = oline.strip()
  1544. # # self.cmd_output.write(oline+"\n")
  1545. # # print oline+"\n"
  1546. # # print >> sys.stderr, oline
  1547. # # oline = p.stdout.readline()
  1548. # #
  1549. # # if p.stdout < 0:
  1550. # # print >> sys.stderr, "Child was terminated by signal", p.stdout
  1551. # # elif p.stdout > 0:
  1552. # # print >> sys.stderr, p.stdout
  1553. # # pass
  1554. # # except OSError, e:
  1555. # # print >> sys.stderr, "Execution failed:", e
  1556. # # try:
  1557. # # os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
  1558. # # cmd = "v.what -a east_north=%d,%d distance=%d map=%@%" % (x,y,100,self.tablename, self.self.mapset)
  1559. # # self.cmd_output.write(cmd+"\n----------\n")
  1560. # # p = Popen(cmd +" --verbose", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
  1561. # #
  1562. # # oline = p.stderr.readline()
  1563. # # while oline:
  1564. # # oline = oline.strip()
  1565. # # oline = p.stderr.readline()
  1566. # # if oline.find("GRASS_INFO_MESSAGE")>-1:
  1567. # # self.cmd_output.write(string.split(oline,maxsplit=1)[1]+"\n")
  1568. # # elif oline.find("GRASS_INFO_WARNING")>-1:
  1569. # # self.cmd_output.write("WARNING: "+string.split(oline,maxsplit=1)[1]+"\n")
  1570. # # elif oline.find("GRASS_INFO_ERROR")>-1:
  1571. # # self.cmd_output.write("ERROR: "+string.split(oline,maxsplit=1)[1]+"\n")
  1572. # #
  1573. # # oline = p.stdout.readline()
  1574. # # while oline:
  1575. # # oline = oline.strip()
  1576. # # self.cmd_output.write(oline+"\n")
  1577. # # print oline+"\n"
  1578. # # print >> sys.stderr, oline
  1579. # # oline = p.stdout.readline()
  1580. # #
  1581. # # if p.stdout < 0:
  1582. # # print >> sys.stderr, "Child was terminated by signal", p.stdout
  1583. # # elif p.stdout > 0:
  1584. # # print >> sys.stderr, p.stdout
  1585. # # pass
  1586. # # except OSError, e:
  1587. # # print >> sys.stderr, "Execution failed:", e
  1588. class TableListCtrl(wx.ListCtrl,
  1589. listmix.ListCtrlAutoWidthMixin):
  1590. # listmix.TextEditMixin):
  1591. """Table description list"""
  1592. def __init__(self, parent, id, table, columns, pos=wx.DefaultPosition,
  1593. size=wx.DefaultSize):
  1594. self.parent = parent
  1595. self.table = table
  1596. self.columns = columns
  1597. wx.ListCtrl.__init__(self, parent, id, pos, size,
  1598. style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
  1599. wx.BORDER_NONE)
  1600. listmix.ListCtrlAutoWidthMixin.__init__(self)
  1601. # listmix.TextEditMixin.__init__(self)
  1602. def Update(self, table, columns):
  1603. """Update column description"""
  1604. self.table = table
  1605. self.columns = columns
  1606. def Populate(self, update=False):
  1607. """Populate the list"""
  1608. itemData = {} # requested by sorter
  1609. if not update:
  1610. headings = [_("Column name"), _("Data type"), _("Data length")]
  1611. i = 0
  1612. for h in headings:
  1613. self.InsertColumn(col=i, heading=h)
  1614. self.SetColumnWidth(col=i, width=150)
  1615. i += 1
  1616. else:
  1617. self.DeleteAllItems()
  1618. i = 0
  1619. for column in self.columns:
  1620. index = self.InsertStringItem(sys.maxint, str(column))
  1621. self.SetStringItem(index, 0, str(column))
  1622. self.SetStringItem(index, 1, str(self.table[column]['type']))
  1623. self.SetStringItem(index, 2, str(self.table[column]['length']))
  1624. self.SetItemData(index, i)
  1625. itemData[i] = (str(column),
  1626. str(self.table[column]['type']),
  1627. int(self.table[column]['length']))
  1628. i = i + 1
  1629. self.SendSizeEvent()
  1630. return itemData
  1631. class LayerListCtrl(wx.ListCtrl,
  1632. listmix.ListCtrlAutoWidthMixin):
  1633. # listmix.ColumnSorterMixin):
  1634. # listmix.TextEditMixin):
  1635. """Layer description list"""
  1636. def __init__(self, parent, id, layers,
  1637. pos=wx.DefaultPosition,
  1638. size=wx.DefaultSize):
  1639. self.parent = parent
  1640. self.layers = layers
  1641. wx.ListCtrl.__init__(self, parent, id, pos, size,
  1642. style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
  1643. wx.BORDER_NONE)
  1644. listmix.ListCtrlAutoWidthMixin.__init__(self)
  1645. # listmix.TextEditMixin.__init__(self)
  1646. def Update(self, layers):
  1647. """Update description"""
  1648. self.layers = layers
  1649. def Populate(self, update=False):
  1650. """Populate the list"""
  1651. itemData = {} # requested by sorter
  1652. if not update:
  1653. headings = [_("Layer"), _("Driver"), _("Database"), _("Table"), _("Key")]
  1654. i = 0
  1655. for h in headings:
  1656. self.InsertColumn(col=i, heading=h)
  1657. i += 1
  1658. else:
  1659. self.DeleteAllItems()
  1660. i = 0
  1661. for layer in self.layers.keys():
  1662. index = self.InsertStringItem(sys.maxint, str(layer))
  1663. self.SetStringItem(index, 0, str(layer))
  1664. database = str(self.layers[layer]['database'])
  1665. driver = str(self.layers[layer]['driver'])
  1666. table = str(self.layers[layer]['table'])
  1667. key = str(self.layers[layer]['key'])
  1668. self.SetStringItem(index, 1, driver)
  1669. self.SetStringItem(index, 2, database)
  1670. self.SetStringItem(index, 3, table)
  1671. self.SetStringItem(index, 4, key)
  1672. self.SetItemData(index, i)
  1673. itemData[i] = (str(layer),
  1674. driver,
  1675. database,
  1676. table,
  1677. key)
  1678. i += 1
  1679. for i in range(self.GetColumnCount()):
  1680. self.SetColumnWidth(col=i, width=wx.LIST_AUTOSIZE)
  1681. if self.GetColumnWidth(col=i) < 60:
  1682. self.SetColumnWidth(col=i, width=60)
  1683. self.SendSizeEvent()
  1684. return itemData
  1685. class LayerBook(wx.Notebook):
  1686. """Manage layers (add, delete, modify)"""
  1687. def __init__(self, parent, id,
  1688. parentDialog,
  1689. style=wx.BK_DEFAULT):
  1690. wx.Notebook.__init__(self, parent, id, style=style)
  1691. self.parent = parent
  1692. self.parentDialog = parentDialog
  1693. self.mapDBInfo = self.parentDialog.mapDBInfo
  1694. #
  1695. # drivers
  1696. #
  1697. cmdDriver = gcmd.Command(['db.drivers',
  1698. '-p',
  1699. '--q'])
  1700. self.listOfDrivers = []
  1701. for drv in cmdDriver.ReadStdOutput():
  1702. self.listOfDrivers.append(drv.strip())
  1703. #
  1704. # get default values
  1705. #
  1706. self.defaultConnect = {}
  1707. cmdConnect = gcmd.Command(['db.connect',
  1708. '-p',
  1709. '--q'])
  1710. for line in cmdConnect.ReadStdOutput():
  1711. item, value = line.split(':')
  1712. self.defaultConnect[item.strip()] = value.strip()
  1713. if len(self.defaultConnect['driver']) == 0 or \
  1714. len(self.defaultConnect['database']) == 0:
  1715. raise gcmd.DBMError(_('Unable to determine default DB connection settings. '
  1716. 'Please define DB connection using db.connect module.'))
  1717. self.defaultTables = self.__getTables(self.defaultConnect['driver'],
  1718. self.defaultConnect['database'])
  1719. try:
  1720. self.defaultColumns = self.__getColumns(self.defaultConnect['driver'],
  1721. self.defaultConnect['database'],
  1722. self.defaultTables[0])
  1723. except IndexError:
  1724. self.defaultColumns = []
  1725. self.__createAddPage()
  1726. self.__createDeletePage()
  1727. self.__createModifyPage()
  1728. def __createAddPage(self):
  1729. """Add new layer"""
  1730. self.addPanel = wx.Panel(parent=self, id=wx.ID_ANY)
  1731. self.AddPage(page=self.addPanel, text=_("Add layer"))
  1732. try:
  1733. maxLayer = max(self.mapDBInfo.layers.keys())
  1734. except ValueError:
  1735. maxLayer = 0
  1736. #
  1737. # list of layer widgets (label, value)
  1738. #
  1739. self.addLayerWidgets = {'layer':
  1740. (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
  1741. label='%s:' % _("Layer")),
  1742. wx.SpinCtrl(parent=self.addPanel, id=wx.ID_ANY, size=(65, -1),
  1743. initial=maxLayer+1,
  1744. min=1, max=1e6)),
  1745. 'driver':
  1746. (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
  1747. label='%s:' % _("Driver")),
  1748. wx.Choice(parent=self.addPanel, id=wx.ID_ANY, size=(200, -1),
  1749. choices=self.listOfDrivers)),
  1750. 'database':
  1751. (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
  1752. label='%s:' % _("Database")),
  1753. wx.TextCtrl(parent=self.addPanel, id=wx.ID_ANY,
  1754. value='',
  1755. style=wx.TE_PROCESS_ENTER)),
  1756. 'table':
  1757. (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
  1758. label='%s:' % _("Table")),
  1759. wx.Choice(parent=self.addPanel, id=wx.ID_ANY, size=(200, -1),
  1760. choices=self.defaultTables)),
  1761. 'key':
  1762. (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
  1763. label='%s:' % _("Key column")),
  1764. wx.Choice(parent=self.addPanel, id=wx.ID_ANY, size=(200, -1),
  1765. choices=self.defaultColumns))}
  1766. # set default values for widgets
  1767. self.addLayerWidgets['driver'][1].SetStringSelection(self.defaultConnect['driver'])
  1768. self.addLayerWidgets['database'][1].SetValue(self.defaultConnect['database'])
  1769. self.addLayerWidgets['table'][1].SetSelection(0)
  1770. self.addLayerWidgets['key'][1].SetSelection(0)
  1771. # events
  1772. self.addLayerWidgets['driver'][1].Bind(wx.EVT_CHOICE, self.OnDriverChanged)
  1773. self.addLayerWidgets['database'][1].Bind(wx.EVT_TEXT_ENTER, self.OnDatabaseChanged)
  1774. self.addLayerWidgets['table'][1].Bind(wx.EVT_CHOICE, self.OnTableChanged)
  1775. #
  1776. # list of table widgets
  1777. #
  1778. self.tableWidgets = {'table': (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
  1779. label='%s:' % _("Table name")),
  1780. wx.TextCtrl(parent=self.addPanel, id=wx.ID_ANY,
  1781. value='',
  1782. style=wx.TE_PROCESS_ENTER)),
  1783. 'key': (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
  1784. label='%s:' % _("Key column")),
  1785. wx.TextCtrl(parent=self.addPanel, id=wx.ID_ANY,
  1786. value='',
  1787. style=wx.TE_PROCESS_ENTER))}
  1788. # events
  1789. self.tableWidgets['table'][1].Bind(wx.EVT_TEXT_ENTER, self.OnCreateTable)
  1790. self.tableWidgets['key'][1].Bind(wx.EVT_TEXT_ENTER, self.OnCreateTable)
  1791. btnTable = wx.Button(self.addPanel, wx.ID_ANY, _("&Create table"),
  1792. size=(125,-1))
  1793. btnTable.Bind(wx.EVT_BUTTON, self.OnCreateTable)
  1794. btnLayer = wx.Button(self.addPanel, wx.ID_ANY, _("&Add layer"),
  1795. size=(125,-1))
  1796. btnLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)
  1797. btnDefault = wx.Button(self.addPanel, wx.ID_ANY, _("&Set default"),
  1798. size=(125,-1))
  1799. btnDefault.Bind(wx.EVT_BUTTON, self.OnSetDefault)
  1800. #
  1801. # do layout
  1802. #
  1803. pageSizer = wx.BoxSizer(wx.HORIZONTAL)
  1804. #
  1805. # layer description
  1806. #
  1807. layerBox = wx.StaticBox (parent=self.addPanel, id=wx.ID_ANY,
  1808. label=" %s " % (_("Layer description")))
  1809. layerSizer = wx.StaticBoxSizer(layerBox, wx.VERTICAL)
  1810. # data area
  1811. dataSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
  1812. dataSizer.AddGrowableCol(1)
  1813. for key in ('layer', 'driver', 'database', 'table', 'key'):
  1814. label, value = self.addLayerWidgets[key]
  1815. dataSizer.Add(item=label,
  1816. flag=wx.ALIGN_CENTER_VERTICAL)
  1817. if label.GetLabel() == "Layer:":
  1818. dataSizer.Add(item=value,
  1819. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
  1820. else:
  1821. dataSizer.Add(item=value,
  1822. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  1823. layerSizer.Add(item=dataSizer,
  1824. proportion=1,
  1825. flag=wx.ALL | wx.EXPAND,
  1826. border=5)
  1827. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1828. btnSizer.Add(item=btnDefault,
  1829. proportion=0,
  1830. flag=wx.ALL | wx.ALIGN_LEFT,
  1831. border=5)
  1832. btnSizer.Add(item=(5,5),
  1833. proportion=1,
  1834. flag=wx.ALL | wx.EXPAND,
  1835. border=5)
  1836. btnSizer.Add(item=btnLayer,
  1837. proportion=0,
  1838. flag=wx.ALL | wx.ALIGN_RIGHT,
  1839. border=5)
  1840. layerSizer.Add(item=btnSizer,
  1841. proportion=0,
  1842. flag=wx.ALL | wx.EXPAND,
  1843. border=0)
  1844. #
  1845. # table description
  1846. #
  1847. tableBox = wx.StaticBox (parent=self.addPanel, id=wx.ID_ANY,
  1848. label=" %s " % (_("Table description")))
  1849. tableSizer = wx.StaticBoxSizer(tableBox, wx.VERTICAL)
  1850. # data area
  1851. dataSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
  1852. dataSizer.AddGrowableCol(1)
  1853. for key in ['table', 'key']:
  1854. label, value = self.tableWidgets[key]
  1855. dataSizer.Add(item=label,
  1856. flag=wx.ALIGN_CENTER_VERTICAL)
  1857. dataSizer.Add(item=value,
  1858. flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  1859. tableSizer.Add(item=dataSizer,
  1860. proportion=1,
  1861. flag=wx.ALL | wx.EXPAND,
  1862. border=5)
  1863. tableSizer.Add(item=btnTable,
  1864. proportion=0,
  1865. flag=wx.ALL | wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT,
  1866. border=5)
  1867. pageSizer.Add(item=layerSizer,
  1868. proportion=1,
  1869. flag=wx.ALL | wx.EXPAND,
  1870. border=5)
  1871. pageSizer.Add(item=tableSizer,
  1872. proportion=1,
  1873. flag=wx.ALL | wx.EXPAND,
  1874. border=5)
  1875. self.addPanel.SetSizer(pageSizer)
  1876. def __createDeletePage(self):
  1877. """Delete layer"""
  1878. self.deletePanel = wx.Panel(parent=self, id=wx.ID_ANY)
  1879. self.AddPage(page=self.deletePanel, text=_("Delete selected layer"))
  1880. label = wx.StaticText(parent=self.deletePanel, id=wx.ID_ANY,
  1881. label='%s:' % _("Layer to detele"))
  1882. self.deleteLayer = wx.ComboBox(parent=self.deletePanel, id=wx.ID_ANY, size=(100, -1),
  1883. style=wx.CB_SIMPLE | wx.CB_READONLY,
  1884. choices=map(str, self.mapDBInfo.layers.keys()))
  1885. self.deleteLayer.SetSelection(0)
  1886. self.deleteLayer.Bind(wx.EVT_COMBOBOX, self.OnChangeLayer)
  1887. try:
  1888. tableName = self.mapDBInfo.layers[int(self.deleteLayer.GetStringSelection())]['table']
  1889. except ValueError:
  1890. tableName = ''
  1891. self.deleteTable = wx.CheckBox(parent=self.deletePanel, id=wx.ID_ANY,
  1892. label=_('Drop also linked attribute table (%s)') % \
  1893. tableName)
  1894. if tableName == '':
  1895. self.deleteLayer.Enable(False)
  1896. self.deleteTable.Enable(False)
  1897. btnDelete = wx.Button(self.deletePanel, wx.ID_DELETE, _("&Delete layer"),
  1898. size=(125,-1))
  1899. btnDelete.Bind(wx.EVT_BUTTON, self.OnDeleteLayer)
  1900. #
  1901. # do layout
  1902. #
  1903. pageSizer = wx.BoxSizer(wx.VERTICAL)
  1904. dataSizer = wx.BoxSizer(wx.VERTICAL)
  1905. flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
  1906. flexSizer.AddGrowableCol(2)
  1907. flexSizer.Add(item=label,
  1908. flag=wx.ALIGN_CENTER_VERTICAL)
  1909. flexSizer.Add(item=self.deleteLayer,
  1910. flag=wx.ALIGN_CENTER_VERTICAL)
  1911. dataSizer.Add(item=flexSizer,
  1912. proportion=0,
  1913. flag=wx.ALL | wx.EXPAND,
  1914. border=5)
  1915. dataSizer.Add(item=self.deleteTable,
  1916. proportion=0,
  1917. flag=wx.ALL | wx.EXPAND,
  1918. border=5)
  1919. pageSizer.Add(item=dataSizer,
  1920. proportion=1,
  1921. flag=wx.ALL | wx.EXPAND,
  1922. border=5)
  1923. pageSizer.Add(item=btnDelete,
  1924. proportion=0,
  1925. flag=wx.ALL | wx.ALIGN_RIGHT,
  1926. border=5)
  1927. self.deletePanel.SetSizer(pageSizer)
  1928. def __createModifyPage(self):
  1929. """Modify layer"""
  1930. self.modifyPanel = wx.Panel(parent=self, id=wx.ID_ANY)
  1931. self.AddPage(page=self.modifyPanel, text=_("Modify selected layer"))
  1932. #
  1933. # list of layer widgets (label, value)
  1934. #
  1935. self.modifyLayerWidgets = {'layer':
  1936. (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
  1937. label='%s:' % _("Layer")),
  1938. wx.ComboBox(parent=self.modifyPanel, id=wx.ID_ANY,
  1939. size=(100, -1),
  1940. style=wx.CB_SIMPLE | wx.CB_READONLY,
  1941. choices=map(str,
  1942. self.mapDBInfo.layers.keys()))),
  1943. 'driver':
  1944. (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
  1945. label='%s:' % _("Driver")),
  1946. wx.Choice(parent=self.modifyPanel, id=wx.ID_ANY,
  1947. size=(200, -1),
  1948. choices=self.listOfDrivers)),
  1949. 'database':
  1950. (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
  1951. label='%s:' % _("Database")),
  1952. wx.TextCtrl(parent=self.modifyPanel, id=wx.ID_ANY,
  1953. value='', size=(350, -1),
  1954. style=wx.TE_PROCESS_ENTER)),
  1955. 'table':
  1956. (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
  1957. label='%s:' % _("Table")),
  1958. wx.Choice(parent=self.modifyPanel, id=wx.ID_ANY,
  1959. size=(200, -1),
  1960. choices=self.defaultTables)),
  1961. 'key':
  1962. (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
  1963. label='%s:' % _("Key column")),
  1964. wx.Choice(parent=self.modifyPanel, id=wx.ID_ANY,
  1965. size=(200, -1),
  1966. choices=self.defaultColumns))}
  1967. # set default values for widgets
  1968. self.modifyLayerWidgets['layer'][1].SetSelection(0)
  1969. try:
  1970. layer = int(self.modifyLayerWidgets['layer'][1].GetStringSelection())
  1971. except ValueError:
  1972. layer = None
  1973. for label in self.modifyLayerWidgets.keys():
  1974. self.modifyLayerWidgets[label][1].Enable(False)
  1975. if layer:
  1976. driver = self.mapDBInfo.layers[layer]['driver']
  1977. database = self.mapDBInfo.layers[layer]['database']
  1978. table = self.mapDBInfo.layers[layer]['table']
  1979. listOfColumns = self.__getColumns(driver, database, table)
  1980. self.modifyLayerWidgets['driver'][1].SetStringSelection(driver)
  1981. self.modifyLayerWidgets['database'][1].SetValue(database)
  1982. if table in self.modifyLayerWidgets['table'][1].GetItems():
  1983. self.modifyLayerWidgets['table'][1].SetStringSelection(table)
  1984. else:
  1985. if self.defaultConnect['schema'] != '':
  1986. table = self.defaultConnect['schema'] + table # try with default schema
  1987. else:
  1988. table = 'public.' + table # try with 'public' schema
  1989. self.modifyLayerWidgets['table'][1].SetStringSelection(table)
  1990. self.modifyLayerWidgets['key'][1].SetItems(listOfColumns)
  1991. self.modifyLayerWidgets['key'][1].SetSelection(0)
  1992. # events
  1993. self.modifyLayerWidgets['layer'][1].Bind(wx.EVT_COMBOBOX, self.OnChangeLayer)
  1994. # self.modifyLayerWidgets['driver'][1].Bind(wx.EVT_CHOICE, self.OnDriverChanged)
  1995. # self.modifyLayerWidgets['database'][1].Bind(wx.EVT_TEXT_ENTER, self.OnDatabaseChanged)
  1996. # self.modifyLayerWidgets['table'][1].Bind(wx.EVT_CHOICE, self.OnTableChanged)
  1997. btnModify = wx.Button(self.modifyPanel, wx.ID_DELETE, _("&Modify layer"),
  1998. size=(125,-1))
  1999. btnModify.Bind(wx.EVT_BUTTON, self.OnModifyLayer)
  2000. #
  2001. # do layout
  2002. #
  2003. pageSizer = wx.BoxSizer(wx.VERTICAL)
  2004. # data area
  2005. dataSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
  2006. dataSizer.AddGrowableCol(1)
  2007. for key in ('layer', 'driver', 'database', 'table', 'key'):
  2008. label, value = self.modifyLayerWidgets[key]
  2009. dataSizer.Add(item=label,
  2010. flag=wx.ALIGN_CENTER_VERTICAL)
  2011. if label.GetLabel() == "Layer:":
  2012. dataSizer.Add(item=value,
  2013. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
  2014. else:
  2015. dataSizer.Add(item=value,
  2016. flag=wx.ALIGN_CENTER_VERTICAL)
  2017. pageSizer.Add(item=dataSizer,
  2018. proportion=1,
  2019. flag=wx.ALL | wx.EXPAND,
  2020. border=5)
  2021. pageSizer.Add(item=btnModify,
  2022. proportion=0,
  2023. flag=wx.ALL | wx.ALIGN_RIGHT,
  2024. border=5)
  2025. self.modifyPanel.SetSizer(pageSizer)
  2026. def __getTables(self, driver, database):
  2027. """Get list of tables for given driver and database"""
  2028. tables = []
  2029. cmdTable = gcmd.Command(['db.tables',
  2030. '-p', '--q',
  2031. 'driver=%s' % driver,
  2032. 'database=%s' % database])
  2033. for table in cmdTable.ReadStdOutput():
  2034. tables.append(table)
  2035. return tables
  2036. def __getColumns(self, driver, database, table):
  2037. """Get list of column of given table"""
  2038. columns = []
  2039. cmdColumn = gcmd.Command(['db.columns',
  2040. '--q',
  2041. 'driver=%s' % driver,
  2042. 'database=%s' % database,
  2043. 'table=%s' % table])
  2044. for column in cmdColumn.ReadStdOutput():
  2045. columns.append(column)
  2046. return columns
  2047. def OnDriverChanged(self, event):
  2048. """Driver selection changed, update list of tables"""
  2049. driver = event.GetString()
  2050. database = self.addLayerWidgets['database'][1].GetValue()
  2051. winTable = self.addLayerWidgets['table'][1]
  2052. winKey = self.addLayerWidgets['key'][1]
  2053. tables = self.__getTables(driver, database)
  2054. winTable.SetItems(tables)
  2055. winTable.SetSelection(0)
  2056. if len(tables) == 0:
  2057. winKey.SetItems([])
  2058. event.Skip()
  2059. def OnDatabaseChanged(self, event):
  2060. """Database selection changed, update list of tables"""
  2061. event.Skip()
  2062. def OnTableChanged(self, event):
  2063. """Table name changed, update list of columns"""
  2064. driver = self.addLayerWidgets['driver'][1].GetStringSelection()
  2065. database = self.addLayerWidgets['database'][1].GetValue()
  2066. table = event.GetString()
  2067. win = self.addLayerWidgets['key'][1]
  2068. cols = self.__getColumns(driver, database, table)
  2069. win.SetItems(cols)
  2070. win.SetSelection(0)
  2071. event.Skip()
  2072. def OnSetDefault(self, event):
  2073. """Set default values"""
  2074. driver = self.addLayerWidgets['driver'][1]
  2075. database = self.addLayerWidgets['database'][1]
  2076. table = self.addLayerWidgets['table'][1]
  2077. key = self.addLayerWidgets['key'][1]
  2078. driver.SetStringSelection(self.defaultConnect['driver'])
  2079. database.SetValue(self.defaultConnect['database'])
  2080. tables = self.__getTables(self.defaultConnect['driver'],
  2081. self.defaultConnect['database'])
  2082. table.SetItems(tables)
  2083. table.SetSelection(0)
  2084. if len(tables) == 0:
  2085. key.SetItems([])
  2086. else:
  2087. cols = self.__getColumns(self.defaultConnect['driver'],
  2088. self.defaultConnect['database'],
  2089. tables[0])
  2090. key.SetItems(cols)
  2091. key.SetSelection(0)
  2092. event.Skip()
  2093. def OnCreateTable(self, event):
  2094. """Create new table (name and key column given)"""
  2095. driver = self.addLayerWidgets['driver'][1].GetStringSelection()
  2096. database = self.addLayerWidgets['database'][1].GetValue()
  2097. table = self.tableWidgets['table'][1].GetValue()
  2098. key = self.tableWidgets['key'][1].GetValue()
  2099. if not table or not key:
  2100. wx.MessageBox(parent=self,
  2101. message=_("Unable to create new table. "
  2102. "Table name or key column name is missing."),
  2103. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  2104. return
  2105. # create table
  2106. sql = 'CREATE TABLE %s (%s INTEGER)' % (table, key)
  2107. gcmd.Command(['db.execute',
  2108. '--q',
  2109. 'driver=%s' % driver,
  2110. 'database=%s' % database],
  2111. stdin=sql)
  2112. # update list of tables
  2113. tableList = self.addLayerWidgets['table'][1]
  2114. tableList.SetItems(self.__getTables(driver, database))
  2115. tableList.SetStringSelection(table)
  2116. # update key column selection
  2117. keyList = self.addLayerWidgets['key'][1]
  2118. keyList.SetItems(self.__getColumns(driver, database, table))
  2119. keyList.SetStringSelection(key)
  2120. event.Skip()
  2121. def OnAddLayer(self, event):
  2122. """Add new layer to vector map"""
  2123. layer = int(self.addLayerWidgets['layer'][1].GetValue())
  2124. layerWin = self.addLayerWidgets['layer'][1]
  2125. driver = self.addLayerWidgets['driver'][1].GetStringSelection()
  2126. database = self.addLayerWidgets['database'][1].GetValue()
  2127. table = self.addLayerWidgets['table'][1].GetStringSelection()
  2128. key = self.addLayerWidgets['key'][1].GetStringSelection()
  2129. if layer in self.mapDBInfo.layers.keys():
  2130. wx.MessageBox(parent=self,
  2131. message=_("Unable to add new layer to vector map <%(vector)s>. "
  2132. "Layer %(layer)d already exists.") %
  2133. {'vector' : self.mapDBInfo.map, 'layer' : layer},
  2134. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  2135. return
  2136. connectCmd = gcmd.Command(['v.db.connect',
  2137. '--q',
  2138. 'map=%s' % self.mapDBInfo.map,
  2139. 'driver=%s' % driver,
  2140. 'database=%s' % database,
  2141. 'table=%s' % table,
  2142. 'key=%s' % key,
  2143. 'layer=%d' % layer])
  2144. if connectCmd.returncode == 0:
  2145. # update dialog (only for new layer)
  2146. self.parentDialog.UpdateDialog(layer=layer)
  2147. # update db info
  2148. self.mapDBInfo = self.parentDialog.mapDBInfo
  2149. # increase layer number
  2150. layerWin.SetValue(layer+1)
  2151. if len(self.mapDBInfo.layers.keys()) == 1:
  2152. # first layer add --- enable previously disabled widgets
  2153. self.deleteLayer.Enable()
  2154. self.deleteTable.Enable()
  2155. for label in self.modifyLayerWidgets.keys():
  2156. self.modifyLayerWidgets[label][1].Enable()
  2157. def OnDeleteLayer(self, event):
  2158. """Delete layer"""
  2159. try:
  2160. layer = int(self.deleteLayer.GetValue())
  2161. except:
  2162. return
  2163. gcmd.Command(['v.db.connect',
  2164. '-d', '--q',
  2165. 'map=%s' % self.mapDBInfo.map,
  2166. 'layer=%d' % layer])
  2167. # drop also table linked to layer which is deleted
  2168. if self.deleteTable.IsChecked():
  2169. driver = self.addLayerWidgets['driver'][1].GetStringSelection()
  2170. database = self.addLayerWidgets['database'][1].GetValue()
  2171. table = self.mapDBInfo.layers[layer]['table']
  2172. sql = 'DROP TABLE %s' % (table)
  2173. gcmd.Command(['db.execute',
  2174. '--q',
  2175. 'driver=%s' % driver,
  2176. 'database=%s' % database],
  2177. stdin=sql)
  2178. # update dialog
  2179. self.parentDialog.UpdateDialog(layer=layer)
  2180. # update db info
  2181. self.mapDBInfo = self.parentDialog.mapDBInfo
  2182. if len(self.mapDBInfo.layers.keys()) == 0:
  2183. # disable selected widgets
  2184. self.deleteLayer.Enable(False)
  2185. self.deleteTable.Enable(False)
  2186. for label in self.modifyLayerWidgets.keys():
  2187. self.modifyLayerWidgets[label][1].Enable(False)
  2188. event.Skip()
  2189. def OnChangeLayer(self, event):
  2190. """Layer number of layer to be deleted is changed"""
  2191. try:
  2192. layer = int(event.GetString())
  2193. except:
  2194. try:
  2195. layer = self.mapDBInfo.layers.keys()[0]
  2196. except:
  2197. return
  2198. if self.GetCurrentPage() == self.modifyPanel:
  2199. driver = self.mapDBInfo.layers[layer]['driver']
  2200. database = self.mapDBInfo.layers[layer]['database']
  2201. table = self.mapDBInfo.layers[layer]['table']
  2202. listOfColumns = self.__getColumns(driver, database, table)
  2203. self.modifyLayerWidgets['driver'][1].SetStringSelection(driver)
  2204. self.modifyLayerWidgets['database'][1].SetValue(database)
  2205. self.modifyLayerWidgets['table'][1].SetStringSelection(table)
  2206. self.modifyLayerWidgets['key'][1].SetItems(listOfColumns)
  2207. self.modifyLayerWidgets['key'][1].SetSelection(0)
  2208. else:
  2209. self.deleteTable.SetLabel(_('Drop also linked attribute table (%s)') % \
  2210. self.mapDBInfo.layers[layer]['table'])
  2211. if event:
  2212. event.Skip()
  2213. def OnModifyLayer(self, event):
  2214. """Modify layer connection settings"""
  2215. layer = int(self.modifyLayerWidgets['layer'][1].GetStringSelection())
  2216. modify = False
  2217. if self.modifyLayerWidgets['driver'][1].GetStringSelection() != \
  2218. self.mapDBInfo.layers[layer]['driver'] or \
  2219. self.modifyLayerWidgets['database'][1].GetStringSelection() != \
  2220. self.mapDBInfo.layers[layer]['database'] or \
  2221. self.modifyLayerWidgets['table'][1].GetStringSelection() != \
  2222. self.mapDBInfo.layers[layer]['table'] or \
  2223. self.modifyLayerWidgets['key'][1].GetStringSelection() != \
  2224. self.mapDBInfo.layers[layer]['key']:
  2225. modify = True
  2226. if modify:
  2227. # delete layer
  2228. gcmd.Command(['v.db.connect',
  2229. '-d', '--q',
  2230. 'map=%s' % self.mapDBInfo.map,
  2231. 'layer=%d' % layer])
  2232. # add modified layer
  2233. gcmd.Command(['v.db.connect',
  2234. '--q',
  2235. 'map=%s' % self.mapDBInfo.map,
  2236. 'driver=%s' % \
  2237. self.modifyLayerWidgets['driver'][1].GetStringSelection(),
  2238. 'database=%s' % \
  2239. self.modifyLayerWidgets['database'][1].GetValue(),
  2240. 'table=%s' % \
  2241. self.modifyLayerWidgets['table'][1].GetStringSelection(),
  2242. 'key=%s' % \
  2243. self.modifyLayerWidgets['key'][1].GetStringSelection(),
  2244. 'layer=%d' % layer])
  2245. # update dialog (only for new layer)
  2246. self.parentDialog.UpdateDialog(layer=layer)
  2247. # update db info
  2248. self.mapDBInfo = self.parentDialog.mapDBInfo
  2249. event.Skip()
  2250. class DisplayAttributesDialog(wx.Dialog):
  2251. """
  2252. Standard dialog used to add/update/display attributes linked
  2253. to the vector map.
  2254. Attribute data can be selected based on layer and category number
  2255. or coordinates.
  2256. @param parent
  2257. @param map vector map
  2258. @param query query coordinates and distance (used for v.edit)
  2259. @param cats {layer: cats}
  2260. @param line feature id (requested for cats)
  2261. @param style
  2262. @param pos
  2263. @param action (add, update, display)
  2264. """
  2265. def __init__(self, parent, map,
  2266. query=None, cats=None, line=None,
  2267. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
  2268. pos=wx.DefaultPosition,
  2269. action="add"):
  2270. self.parent = parent # mapdisplay.BufferedWindow
  2271. self.map = map
  2272. self.action = action
  2273. # id of selected line
  2274. self.line = None
  2275. # get layer/table/column information
  2276. self.mapDBInfo = VectorDBInfo(self.map)
  2277. layers = self.mapDBInfo.layers.keys() # get available layers
  2278. # check if db connection / layer exists
  2279. if len(layers) <= 0:
  2280. label = _("Database connection "
  2281. "is not defined in DB file.")
  2282. wx.MessageBox(parent=self.parent,
  2283. message=_("No attribute table linked to "
  2284. "vector map <%(vector)s> found. %(msg)s"
  2285. "\nYou can disable this message from digitization settings. Or "
  2286. "you can create and link attribute table to the vector map "
  2287. "using Attribute Table Manager.") %
  2288. {'vector' : self.map, 'msg' : label},
  2289. caption=_("Message"), style=wx.OK | wx.ICON_EXCLAMATION | wx.CENTRE)
  2290. self.mapDBInfo = None
  2291. return
  2292. wx.Dialog.__init__(self, parent=self.parent, id=wx.ID_ANY,
  2293. title="", style=style, pos=pos)
  2294. # dialog body
  2295. mainSizer = wx.BoxSizer(wx.VERTICAL)
  2296. # notebook
  2297. self.notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
  2298. self.closeDialog = wx.CheckBox(parent=self, id=wx.ID_ANY,
  2299. label=_("Close dialog on submit"))
  2300. self.closeDialog.SetValue(True)
  2301. self.UpdateDialog(query, cats, line)
  2302. # set title
  2303. if self.action == "update":
  2304. self.SetTitle(_("Update attributes"))
  2305. elif self.action == "add":
  2306. self.SetTitle(_("Add attributes"))
  2307. else:
  2308. self.SetTitle(_("Display attributes"))
  2309. # buttons
  2310. btnCancel = wx.Button(self, wx.ID_CANCEL)
  2311. btnReset = wx.Button(self, wx.ID_UNDO, _("&Reload"))
  2312. btnSubmit = wx.Button(self, wx.ID_OK, _("&Submit"))
  2313. btnSizer = wx.StdDialogButtonSizer()
  2314. btnSizer.AddButton(btnCancel)
  2315. btnSizer.AddButton(btnReset)
  2316. btnSizer.SetNegativeButton(btnReset)
  2317. btnSubmit.SetDefault()
  2318. btnSizer.AddButton(btnSubmit)
  2319. btnSizer.Realize()
  2320. mainSizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
  2321. mainSizer.Add(item=self.closeDialog, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
  2322. border=5)
  2323. mainSizer.Add(item=btnSizer, proportion=0,
  2324. flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
  2325. # bindigs
  2326. btnReset.Bind(wx.EVT_BUTTON, self.OnReset)
  2327. btnSubmit.Bind(wx.EVT_BUTTON, self.OnSubmit)
  2328. btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  2329. self.SetSizer(mainSizer)
  2330. mainSizer.Fit(self)
  2331. # set min size for dialog
  2332. self.SetMinSize(self.GetBestSize())
  2333. if self.notebook.GetPageCount() == 0:
  2334. Debug.msg(2, "DisplayAttributesDialog(): Nothing found!")
  2335. self.mapDBInfo = None
  2336. def __SelectAttributes(self, layer):
  2337. """Select attributes"""
  2338. pass
  2339. def OnSQLStatement(self, event):
  2340. """Update SQL statement"""
  2341. pass
  2342. def GetSQLString(self, updateValues=False):
  2343. """Create SQL statement string based on self.sqlStatement
  2344. If updateValues is True, update dataFrame according to values
  2345. in textfields.
  2346. """
  2347. sqlCommands = []
  2348. # find updated values for each layer/category
  2349. for layer in self.mapDBInfo.layers.keys(): # for each layer
  2350. table = self.mapDBInfo.layers[layer]["table"]
  2351. key = self.mapDBInfo.layers[layer]["key"]
  2352. columns = self.mapDBInfo.tables[table]
  2353. for idx in range(len(columns[key]['values'])): # for each category
  2354. updatedColumns = []
  2355. updatedValues = []
  2356. for name in columns.keys():
  2357. if name == key:
  2358. cat = columns[name]['values'][idx]
  2359. continue
  2360. type = columns[name]['type']
  2361. value = columns[name]['values'][idx]
  2362. id = columns[name]['ids'][idx]
  2363. try:
  2364. newvalue = self.FindWindowById(id).GetValue()
  2365. except:
  2366. newvalue = self.FindWindowById(id).GetLabel()
  2367. if newvalue == '':
  2368. newvalue = None
  2369. if newvalue != value:
  2370. updatedColumns.append(name)
  2371. if newvalue is None:
  2372. updatedValues.append('NULL')
  2373. else:
  2374. if type != 'character':
  2375. updatedValues.append(newvalue)
  2376. else:
  2377. updatedValues.append("'" + newvalue + "'")
  2378. columns[name]['values'][idx] = newvalue
  2379. if self.action != "add" and len(updatedValues) == 0:
  2380. continue
  2381. if self.action == "add":
  2382. sqlString = "INSERT INTO %s (%s," % (table, key)
  2383. else:
  2384. sqlString = "UPDATE %s SET " % table
  2385. for idx in range(len(updatedColumns)):
  2386. name = updatedColumns[idx]
  2387. if self.action == "add":
  2388. sqlString += name + ","
  2389. else:
  2390. sqlString += name + "=" + updatedValues[idx] + ","
  2391. sqlString = sqlString[:-1] # remove last comma
  2392. if self.action == "add":
  2393. sqlString += ") VALUES (%s," % cat
  2394. for value in updatedValues:
  2395. sqlString += str(value) + ","
  2396. sqlString = sqlString[:-1] # remove last comma
  2397. sqlString += ")"
  2398. else:
  2399. sqlString += " WHERE cat=%s" % cat
  2400. sqlCommands.append(sqlString)
  2401. # for each category
  2402. # for each layer END
  2403. Debug.msg(3, "DisplayAttributesDialog.GetSQLString(): %s" % sqlCommands)
  2404. return sqlCommands
  2405. def OnReset(self, event):
  2406. """Reset form"""
  2407. for layer in self.mapDBInfo.layers.keys():
  2408. table = self.mapDBInfo.layers[layer]["table"]
  2409. key = self.mapDBInfo.layers[layer]["key"]
  2410. columns = self.mapDBInfo.tables[table]
  2411. for idx in range(len(columns[key]['values'])):
  2412. for name in columns.keys():
  2413. type = columns[name]['type']
  2414. value = columns[name]['values'][idx]
  2415. id = columns[name]['ids'][idx]
  2416. if name != key:
  2417. self.FindWindowById(id).SetValue(str(value))
  2418. def OnCancel(self, event):
  2419. """Cancel button pressed"""
  2420. self.parent.parent.dialogs['attributes'] = None
  2421. if self.parent.parent.digit:
  2422. self.parent.parent.digit.driver.SetSelected([])
  2423. self.parent.UpdateMap(render=False)
  2424. else:
  2425. self.parent.parent.OnRender(None)
  2426. self.Close()
  2427. def OnSubmit(self, event):
  2428. """Submit records"""
  2429. sqlCommands = self.GetSQLString(updateValues=True)
  2430. if len(sqlCommands) > 0:
  2431. sqlfile = tempfile.NamedTemporaryFile(mode="w")
  2432. for sql in sqlCommands:
  2433. sqlfile.file.write(sql + ";\n")
  2434. sqlfile.file.flush()
  2435. gcmd.Command(cmd=["db.execute",
  2436. "--q",
  2437. "input=%s" % sqlfile.name])
  2438. if self.closeDialog.IsChecked():
  2439. self.OnCancel(event)
  2440. def GetLine(self):
  2441. """Get id of selected vector object or 'None' if nothing selected"""
  2442. return self.line
  2443. def UpdateDialog(self, query=None, cats=None, line=None):
  2444. """Update dialog
  2445. Return True if updated otherwise False
  2446. """
  2447. self.line = line
  2448. if not self.mapDBInfo:
  2449. return False
  2450. self.mapDBInfo.Reset()
  2451. layers = self.mapDBInfo.layers.keys() # get available layers
  2452. # id of selected line
  2453. if query: # select by position
  2454. self.line, nselected = self.mapDBInfo.SelectByPoint(query[0],
  2455. query[1])
  2456. # reset notebook
  2457. self.notebook.DeleteAllPages()
  2458. for layer in layers: # for each layer
  2459. if not query: # select by layer/cat
  2460. if cats.has_key(layer):
  2461. for cat in cats[layer]:
  2462. nselected = self.mapDBInfo.SelectFromTable(layer,
  2463. where="%s=%d" % \
  2464. (self.mapDBInfo.layers[layer]['key'],
  2465. cat))
  2466. else:
  2467. nselected = 0
  2468. # if nselected <= 0 and self.action != "add":
  2469. # continue # nothing selected ...
  2470. if self.action == "add":
  2471. if nselected <= 0:
  2472. if cats.has_key(layer):
  2473. table = self.mapDBInfo.layers[layer]["table"]
  2474. key = self.mapDBInfo.layers[layer]["key"]
  2475. columns = self.mapDBInfo.tables[table]
  2476. for name in columns.keys():
  2477. if name == key:
  2478. for cat in cats[layer]:
  2479. self.mapDBInfo.tables[table][name]['values'].append(cat)
  2480. else:
  2481. self.mapDBInfo.tables[table][name]['values'].append(None)
  2482. else: # change status 'add' -> 'update'
  2483. self.action = "update"
  2484. # use scrolled panel instead (and fix initial max height of the window to 480px)
  2485. ### panel = wx.Panel(parent=self.notebook, id=wx.ID_ANY)
  2486. panel = scrolled.ScrolledPanel(parent=self.notebook, id=wx.ID_ANY,
  2487. size=(-1, 150))
  2488. panel.SetupScrolling(scroll_x=False)
  2489. self.notebook.AddPage(page=panel, text=" %s %d " % (_("Layer"), layer))
  2490. # notebook body
  2491. border = wx.BoxSizer(wx.VERTICAL)
  2492. table = self.mapDBInfo.layers[layer]["table"]
  2493. key = self.mapDBInfo.layers[layer]["key"]
  2494. columns = self.mapDBInfo.tables[table]
  2495. # value
  2496. if len(columns[key]['values']) == 0: # no cats
  2497. sizer = wx.BoxSizer(wx.VERTICAL)
  2498. txt = wx.StaticText(parent=panel, id=wx.ID_ANY,
  2499. label=_("No database record available."))
  2500. sizer.Add(txt, proportion=1,
  2501. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER | wx.EXPAND)
  2502. border.Add(item=sizer, proportion=1,
  2503. flag=wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER,
  2504. border=10)
  2505. panel.SetSizer(border)
  2506. continue
  2507. for idx in range(len(columns[key]['values'])):
  2508. flexSizer = wx.FlexGridSizer (cols=4, hgap=3, vgap=3)
  2509. flexSizer.AddGrowableCol(3)
  2510. # columns
  2511. for name in columns.keys():
  2512. vtype = columns[name]['type']
  2513. if columns[name]['values'][idx] is not None:
  2514. value = str(columns[name]['values'][idx])
  2515. else:
  2516. value = ''
  2517. if name == key:
  2518. box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
  2519. label=" %s %s " % (_("Category"), value))
  2520. boxFont = self.GetFont()
  2521. boxFont.SetWeight(wx.FONTWEIGHT_BOLD)
  2522. box.SetFont(boxFont)
  2523. sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2524. colValue = box
  2525. else:
  2526. colName = wx.StaticText(parent=panel, id=wx.ID_ANY,
  2527. label=name)
  2528. colType = wx.StaticText(parent=panel, id=wx.ID_ANY,
  2529. label="[" + vtype.lower() + "]")
  2530. delimiter = wx.StaticText(parent=panel, id=wx.ID_ANY, label=":")
  2531. colValue = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value=value) # TODO: validator
  2532. colValue.SetName(name)
  2533. self.Bind(wx.EVT_TEXT, self.OnSQLStatement, colValue)
  2534. flexSizer.Add(colName, proportion=0,
  2535. flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
  2536. flexSizer.Add(colType, proportion=0,
  2537. flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
  2538. flexSizer.Add(delimiter, proportion=0,
  2539. flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
  2540. flexSizer.Add(colValue, proportion=1,
  2541. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  2542. # add widget reference to self.columns
  2543. columns[name]['ids'].append(colValue.GetId()) # name, type, values, id
  2544. # for each attribute (including category) END
  2545. sizer.Add(item=flexSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=1)
  2546. border.Add(item=sizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
  2547. # for each category END
  2548. panel.SetSizer(border)
  2549. # for each layer END
  2550. self.Layout()
  2551. return True
  2552. class VectorDBInfo:
  2553. """Class providing information about attribute tables
  2554. linked to the vector map"""
  2555. def __init__(self, map):
  2556. self.map = map
  2557. # {layer number : {table, database, driver})
  2558. self.layers = {}
  2559. # {table : {column name : type, length, values, ids}}
  2560. self.tables = {}
  2561. if not self.__CheckDBConnection(): # -> self.layers
  2562. return
  2563. self.__DescribeTables() # -> self.tables
  2564. def __CheckDBConnection(self):
  2565. """Check DB connection"""
  2566. layerCommand = gcmd.Command(cmd=["v.db.connect",
  2567. "-g", "--q",
  2568. "map=%s" % self.map],
  2569. rerr=None, stderr=None)
  2570. if layerCommand.returncode != 0:
  2571. return False
  2572. # list of available layers & (table, database, driver)
  2573. for line in layerCommand.ReadStdOutput():
  2574. lineList = line.split(' ')
  2575. layer = lineList[0]
  2576. if '/' in layer:
  2577. layer, layer_name = lineList[0].split('/')
  2578. else:
  2579. layer_name = None
  2580. # database can contain ' ' in it's path
  2581. if len(lineList) > 5:
  2582. database = ''.join(lineList[3:-1])
  2583. else:
  2584. database = lineList[3]
  2585. self.layers[int(layer)] = {
  2586. "name" : layer_name,
  2587. "table" : lineList[1],
  2588. "key" : lineList[2],
  2589. "database" : database,
  2590. "driver" : lineList[-1]
  2591. }
  2592. if (len(self.layers.keys()) == 0):
  2593. return False
  2594. return True
  2595. def __DescribeTables(self):
  2596. """Describe linked tables"""
  2597. for layer in self.layers.keys():
  2598. # determine column names and types
  2599. table = self.layers[layer]["table"]
  2600. columnsCommand = gcmd.Command (cmd=["db.describe",
  2601. "-c", "--q",
  2602. "table=%s" % self.layers[layer]["table"],
  2603. "driver=%s" % self.layers[layer]["driver"],
  2604. "database=%s" % self.layers[layer]["database"]])
  2605. columns = {} # {name: {type, length, [values], [ids]}}
  2606. if columnsCommand.returncode == 0:
  2607. # skip nrows and ncols
  2608. i = 0
  2609. for line in columnsCommand.ReadStdOutput()[2:]:
  2610. num, name, type, length = line.strip().split(':')
  2611. # FIXME: support more datatypes
  2612. if type.lower() == "integer":
  2613. ctype = int
  2614. elif type.lower() == "double precision":
  2615. ctype = float
  2616. else:
  2617. ctype = str
  2618. columns[name.strip()] = { 'index' : i,
  2619. 'type' : type.lower(),
  2620. 'ctype' : ctype,
  2621. 'length' : int(length),
  2622. 'values' : [],
  2623. 'ids' : []}
  2624. i += 1
  2625. else:
  2626. return False
  2627. # check for key column
  2628. # v.db.connect -g/p returns always key column name lowercase
  2629. if self.layers[layer]["key"] not in columns.keys():
  2630. for col in columns.keys():
  2631. if col.lower() == self.layers[layer]["key"]:
  2632. self.layers[layer]["key"] = col.upper()
  2633. break
  2634. self.tables[table] = columns
  2635. return True
  2636. def GetColumns(self, table):
  2637. """Return list of columns names (based on their index)"""
  2638. names = [''] * len(self.tables[table].keys())
  2639. for name, desc in self.tables[table].iteritems():
  2640. names[desc['index']] = name
  2641. return names
  2642. def SelectByPoint(self, queryCoords, qdist):
  2643. """Get attributes by coordinates (all available layers)
  2644. Return line id or None if no line is found"""
  2645. line = None
  2646. nselected = 0
  2647. cmdWhat = gcmd.Command(cmd=['v.what',
  2648. '-a', '--q',
  2649. 'map=%s' % self.map,
  2650. 'east_north=%f,%f' % \
  2651. (float(queryCoords[0]), float(queryCoords[1])),
  2652. 'distance=%f' % qdist], stderr=None)
  2653. if cmdWhat.returncode == 0:
  2654. read = False
  2655. for item in cmdWhat.ReadStdOutput():
  2656. litem = item.lower()
  2657. if read:
  2658. name, value = item.split(':')
  2659. name = name.strip()
  2660. # append value to the column
  2661. try:
  2662. # casting ...
  2663. value = self.tables[table][name]['ctype'] (value.strip())
  2664. self.tables[table][name]['values'].append(value)
  2665. except:
  2666. read = False
  2667. if "line:" in litem: # get line id
  2668. line = int(item.split(':')[1].strip())
  2669. elif "key column:" in litem: # start reading attributes
  2670. read = True
  2671. nselected = nselected + 1
  2672. elif "layer:" in litem: # get layer id
  2673. layer = int(item.split(':')[1].strip())
  2674. table = self.layers[layer]["table"] # get table desc
  2675. read = False
  2676. return (line, nselected)
  2677. def SelectFromTable(self, layer, cols='*', where=None):
  2678. """Select records from the table
  2679. Return number of selected records, -1 on error
  2680. """
  2681. if layer <= 0:
  2682. return -1
  2683. nselected = 0
  2684. table = self.layers[layer]["table"] # get table desc
  2685. # select values (only one record)
  2686. if where is None or where is '':
  2687. sql="SELECT %s FROM %s" % (cols, table)
  2688. else:
  2689. sql="SELECT %s FROM %s WHERE %s" % (cols, table, where)
  2690. selectCommand = gcmd.Command(["db.select", "-v", "--q",
  2691. "sql=%s" % sql,
  2692. "database=%s" % self.layers[layer]["database"],
  2693. "driver=%s" % self.layers[layer]["driver"]])
  2694. # self.tables[table][key][1] = str(cat)
  2695. if selectCommand.returncode == 0:
  2696. for line in selectCommand.ReadStdOutput():
  2697. name, value = line.split('|')
  2698. # casting ...
  2699. if value:
  2700. value = self.tables[table][name]['ctype'] (value)
  2701. else:
  2702. value = None
  2703. self.tables[table][name]['values'].append(value)
  2704. nselected = 1
  2705. return nselected
  2706. def Reset(self):
  2707. """Reset"""
  2708. for layer in self.layers:
  2709. table = self.layers[layer]["table"] # get table desc
  2710. columns = self.tables[table]
  2711. for name in self.tables[table].keys():
  2712. self.tables[table][name]['values'] = []
  2713. self.tables[table][name]['ids'] = []
  2714. class ModifyTableRecord(wx.Dialog):
  2715. """Dialog for inserting/updating table record"""
  2716. def __init__(self, parent, id, title, data, keyEditable=(-1, True),
  2717. style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
  2718. """
  2719. Notes:
  2720. 'Data' is a list: [(column, value)]
  2721. 'KeyEditable' (id, editable?) indicates if textarea for key column
  2722. is editable(True) or not.
  2723. """
  2724. wx.Dialog.__init__(self, parent, id, title, style=style)
  2725. self.keyId = keyEditable[0]
  2726. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  2727. self.dataPanel = scrolled.ScrolledPanel(parent=self.panel, id=wx.ID_ANY,
  2728. style=wx.TAB_TRAVERSAL)
  2729. self.dataPanel.SetupScrolling(scroll_x=False)
  2730. #
  2731. # buttons
  2732. #
  2733. self.btnCancel = wx.Button(self.panel, wx.ID_CANCEL)
  2734. self.btnSubmit = wx.Button(self.panel, wx.ID_OK, _("Submit"))
  2735. self.btnSubmit.SetDefault()
  2736. #
  2737. # data area
  2738. #
  2739. self.widgets = []
  2740. id = 0
  2741. self.box = False
  2742. self.cat = None
  2743. for column, value in data:
  2744. if keyEditable[0] == id:
  2745. self.cat = int(value)
  2746. if keyEditable[1] == False:
  2747. self.box = True
  2748. id += 1
  2749. continue
  2750. else:
  2751. valueWin = wx.SpinCtrl(parent=self.dataPanel, id=wx.ID_ANY,
  2752. value=value, min=-1e9, max=1e9, size=(250, -1))
  2753. else:
  2754. valueWin = wx.TextCtrl(parent=self.dataPanel, id=wx.ID_ANY,
  2755. value=value, size=(250, -1))
  2756. label = wx.StaticText(parent=self.dataPanel, id=wx.ID_ANY,
  2757. label=column + ":")
  2758. self.widgets.append((label.GetId(),
  2759. valueWin.GetId()))
  2760. id += 1
  2761. self.__Layout()
  2762. # winSize = self.GetSize()
  2763. # fix height of window frame if needed
  2764. # if winSize[1] > 480:
  2765. # winSize[1] = 480
  2766. # self.SetSize(winSize)
  2767. # self.SetMinSize(winSize)
  2768. def __Layout(self):
  2769. """Do layout"""
  2770. sizer = wx.BoxSizer(wx.VERTICAL)
  2771. if self.box:
  2772. box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  2773. label=" %s %d " % (_("Category"), self.cat))
  2774. boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
  2775. # data area
  2776. dataSizer = wx.FlexGridSizer (cols=2, hgap=3, vgap=3)
  2777. dataSizer.AddGrowableCol(1)
  2778. for labelId, valueId in self.widgets:
  2779. label = self.FindWindowById(labelId)
  2780. value = self.FindWindowById(valueId)
  2781. dataSizer.Add(label, proportion=0,
  2782. flag=wx.ALIGN_CENTER_VERTICAL)
  2783. dataSizer.Add(value, proportion=0,
  2784. flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  2785. self.dataPanel.SetAutoLayout(True)
  2786. self.dataPanel.SetSizer(dataSizer)
  2787. dataSizer.Fit(self.dataPanel)
  2788. if self.box:
  2789. boxSizer.Add(item=self.dataPanel, proportion=1,
  2790. flag=wx.EXPAND | wx.ALL, border=5)
  2791. # buttons
  2792. btnSizer = wx.StdDialogButtonSizer()
  2793. btnSizer.AddButton(self.btnCancel)
  2794. btnSizer.AddButton(self.btnSubmit)
  2795. btnSizer.Realize()
  2796. if not self.box:
  2797. sizer.Add(item=self.dataPanel, proportion=1,
  2798. flag=wx.EXPAND | wx.ALL, border=5)
  2799. else:
  2800. sizer.Add(item=boxSizer, proportion=1,
  2801. flag=wx.EXPAND | wx.ALL, border=5)
  2802. sizer.Add(item=btnSizer, proportion=0,
  2803. flag=wx.EXPAND | wx.ALL, border=5)
  2804. #sizer.SetSizeHints(self.panel)
  2805. self.panel.SetAutoLayout(True)
  2806. self.panel.SetSizer(sizer)
  2807. sizer.Fit(self.panel)
  2808. self.Layout()
  2809. # set window frame size (min & max)
  2810. minFrameHeight = 150
  2811. maxFrameHeight = 2 * minFrameHeight
  2812. if self.GetSize()[1] > minFrameHeight:
  2813. self.SetMinSize((self.GetSize()[0], minFrameHeight))
  2814. else:
  2815. self.SetMinSize(self.GetSize())
  2816. if self.GetSize()[1] > maxFrameHeight:
  2817. self.SetSize((self.GetSize()[0], maxFrameHeight))
  2818. else:
  2819. self.SetSize(self.panel.GetSize())
  2820. def GetValues(self, columns=None):
  2821. """Return list of values (casted to string).
  2822. If columns is given (list), return only values of given columns.
  2823. """
  2824. valueList = []
  2825. for labelId, valueId in self.widgets:
  2826. column = self.FindWindowById(labelId).GetLabel().replace(':', '')
  2827. if columns is None or column in columns:
  2828. value = str(self.FindWindowById(valueId).GetValue()) # -> string
  2829. valueList.append(value)
  2830. # add key value
  2831. if self.box:
  2832. valueList.insert(self.keyId, str(self.cat))
  2833. return valueList
  2834. def main(argv=None):
  2835. if argv is None:
  2836. argv = sys.argv
  2837. if len(argv) != 2:
  2838. print >> sys.stderr, __doc__
  2839. sys.exit()
  2840. # Command line arguments of the script to be run are preserved by the
  2841. # hotswap.py wrapper but hotswap.py and its options are removed that
  2842. # sys.argv looks as if no wrapper was present.
  2843. #print "argv:", `argv`
  2844. #some applications might require image handlers
  2845. wx.InitAllImageHandlers()
  2846. app = wx.PySimpleApp()
  2847. f = AttributeManager(parent=None, id=wx.ID_ANY,
  2848. title="%s - <%s>" % (_("GRASS GIS Attribute Table Manager"),
  2849. argv[1]),
  2850. size=(900,600), vectmap=argv[1])
  2851. f.Show()
  2852. app.MainLoop()
  2853. if __name__ == '__main__':
  2854. main()