menuform.py 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187
  1. #!/usr/bin/env python
  2. """
  3. @brief Construct simple wxPython GUI from a GRASS command interface
  4. description.
  5. Classes:
  6. - helpPanel
  7. - mainFrame
  8. - cmdPanel
  9. - GrassGUIApp
  10. - GUI
  11. - FloatValidator
  12. - GNotebook
  13. This program is just a coarse approach to automatically build a GUI
  14. from a xml-based GRASS user interface description.
  15. You need to have Python 2.4, wxPython 2.8 and python-xml.
  16. The XML stream is read from executing the command given in the
  17. command line, thus you may call it for instance this way:
  18. python <this file.py> r.basins.fill
  19. Or you set an alias or wrap the call up in a nice shell script, GUI
  20. environment ... please contribute your idea.
  21. Updated to wxPython 2.8 syntax and contrib widgets. Methods added to
  22. make it callable by gui. Method added to automatically re-run with
  23. pythonw on a Mac.
  24. @todo
  25. - verify option value types
  26. Copyright(C) 2000-2011 by the GRASS Development Team
  27. This program is free software under the GPL(>=v2) Read the file
  28. COPYING coming with GRASS for details.
  29. @author Jan-Oliver Wagner <jan@intevation.de>
  30. @author Bernhard Reiter <bernhard@intevation.de>
  31. @author Michael Barton, Arizona State University
  32. @author Daniel Calvelo <dca.gis@gmail.com>
  33. @author Martin Landa <landa.martin@gmail.com>
  34. """
  35. import sys
  36. import re
  37. import string
  38. import textwrap
  39. import os
  40. import time
  41. import types
  42. import copy
  43. import locale
  44. import types
  45. from threading import Thread
  46. import Queue
  47. import tempfile
  48. import globalvar
  49. import wx
  50. import wx.html
  51. try:
  52. import wx.lib.agw.flatnotebook as FN
  53. except ImportError:
  54. import wx.lib.flatnotebook as FN
  55. import wx.lib.colourselect as csel
  56. import wx.lib.filebrowsebutton as filebrowse
  57. import wx.lib.scrolledpanel as scrolled
  58. from wx.lib.expando import ExpandoTextCtrl, EVT_ETC_LAYOUT_NEEDED
  59. from wx.lib.newevent import NewEvent
  60. try:
  61. import xml.etree.ElementTree as etree
  62. except ImportError:
  63. import elementtree.ElementTree as etree # Python <= 2.4
  64. import gdialogs
  65. from ghelp import HelpPanel
  66. gisbase = os.getenv("GISBASE")
  67. if gisbase is None:
  68. print >>sys.stderr, "We don't seem to be properly installed, or we are being run outside GRASS. Expect glitches."
  69. gisbase = os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)
  70. wxbase = gisbase
  71. else:
  72. wxbase = os.path.join(globalvar.ETCWXDIR)
  73. sys.path.append(wxbase)
  74. from grass.script import core as grass
  75. from grass.script import task as gtask
  76. import gselect
  77. import gcmd
  78. import goutput
  79. import utils
  80. from preferences import globalSettings as UserSettings
  81. try:
  82. import subprocess
  83. except:
  84. from compat import subprocess
  85. wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
  86. # From lib/gis/col_str.c, except purple which is mentioned
  87. # there but not given RGB values
  88. str2rgb = {'aqua': (100, 128, 255),
  89. 'black': (0, 0, 0),
  90. 'blue': (0, 0, 255),
  91. 'brown': (180, 77, 25),
  92. 'cyan': (0, 255, 255),
  93. 'gray': (128, 128, 128),
  94. 'green': (0, 255, 0),
  95. 'grey': (128, 128, 128),
  96. 'indigo': (0, 128, 255),
  97. 'magenta': (255, 0, 255),
  98. 'orange': (255, 128, 0),
  99. 'purple': (128, 0, 128),
  100. 'red': (255, 0, 0),
  101. 'violet': (128, 0, 255),
  102. 'white': (255, 255, 255),
  103. 'yellow': (255, 255, 0)}
  104. rgb2str = {}
  105. for (s,r) in str2rgb.items():
  106. rgb2str[ r ] = s
  107. """!Hide some options in the GUI"""
  108. #_blackList = { 'enabled' : False,
  109. # 'items' : { 'r.buffer' : {'params' : ['input', 'output'],
  110. # 'flags' : ['z', 'overwrite']}}}
  111. _blackList = { 'enabled' : False,
  112. 'items' : {} }
  113. def color_resolve(color):
  114. if len(color) > 0 and color[0] in "0123456789":
  115. rgb = tuple(map(int, color.split(':')))
  116. label = color
  117. else:
  118. # Convert color names to RGB
  119. try:
  120. rgb = str2rgb[color]
  121. label = color
  122. except KeyError:
  123. rgb = (200, 200, 200)
  124. label = _('Select Color')
  125. return (rgb, label)
  126. def text_beautify(someString , width = 70):
  127. """!Make really long texts shorter, clean up whitespace and remove
  128. trailing punctuation.
  129. """
  130. if width > 0:
  131. return escape_ampersand(string.strip(
  132. os.linesep.join(textwrap.wrap(utils.normalize_whitespace(someString), width)),
  133. ".,;:"))
  134. else:
  135. return escape_ampersand(string.strip(utils.normalize_whitespace(someString), ".,;:"))
  136. def escape_ampersand(text):
  137. """!Escapes ampersands with additional ampersand for GUI"""
  138. return string.replace(text, "&", "&&")
  139. class UpdateThread(Thread):
  140. """!Update dialog widgets in the thread"""
  141. def __init__(self, parent, event, eventId, task):
  142. Thread.__init__(self)
  143. self.parent = parent
  144. self.event = event
  145. self.eventId = eventId
  146. self.task = task
  147. self.setDaemon(True)
  148. # list of functions which updates the dialog
  149. self.data = {}
  150. def run(self):
  151. # get widget id
  152. if not self.eventId:
  153. for p in self.task.params:
  154. if p.get('gisprompt', False) == False:
  155. continue
  156. prompt = p.get('element', '')
  157. if prompt == 'vector':
  158. name = p.get('name', '')
  159. if name in ('map', 'input'):
  160. self.eventId = p['wxId'][0]
  161. if self.eventId is None:
  162. return
  163. p = self.task.get_param(self.eventId, element = 'wxId', raiseError = False)
  164. if not p or 'wxId-bind' not in p:
  165. return
  166. # get widget prompt
  167. pType = p.get('prompt', '')
  168. if not pType:
  169. return
  170. # check for map/input parameter
  171. pMap = self.task.get_param('map', raiseError = False)
  172. if not pMap:
  173. pMap = self.task.get_param('input', raiseError = False)
  174. if pMap:
  175. map = pMap.get('value', '')
  176. else:
  177. map = None
  178. # avoid running db.describe several times
  179. cparams = dict()
  180. cparams[map] = { 'dbInfo' : None,
  181. 'layers' : None, }
  182. # update reference widgets
  183. for uid in p['wxId-bind']:
  184. win = self.parent.FindWindowById(uid)
  185. name = win.GetName()
  186. map = layer = None
  187. driver = db = table = None
  188. if name in ('LayerSelect', 'ColumnSelect'):
  189. if p.get('element', '') == 'vector': # -> vector
  190. # get map name
  191. map = p.get('value', '')
  192. # get layer
  193. for bid in p['wxId-bind']:
  194. p = self.task.get_param(bid, element = 'wxId', raiseError = False)
  195. if not p:
  196. continue
  197. if p.get('element', '') == 'layer':
  198. layer = p.get('value', '')
  199. if layer != '':
  200. layer = p.get('value', '')
  201. else:
  202. layer = p.get('default', '')
  203. break
  204. elif p.get('element', '') == 'layer': # -> layer
  205. # get layer
  206. layer = p.get('value', '')
  207. if layer != '':
  208. layer = p.get('value', '')
  209. else:
  210. layer = p.get('default', '')
  211. # get map name
  212. pMap = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  213. if pMap:
  214. map = pMap.get('value', '')
  215. if name == 'TableSelect' or \
  216. (name == 'ColumnSelect' and not map):
  217. pDriver = self.task.get_param('dbdriver', element = 'prompt', raiseError = False)
  218. if pDriver:
  219. driver = pDriver.get('value', '')
  220. pDb = self.task.get_param('dbname', element = 'prompt', raiseError = False)
  221. if pDb:
  222. db = pDb.get('value', '')
  223. if name == 'ColumnSelect':
  224. pTable = self.task.get_param('dbtable', element = 'element', raiseError = False)
  225. if pTable:
  226. table = pTable.get('value', '')
  227. if name == 'LayerSelect':
  228. # determine format
  229. native = True
  230. for id in pMap['wxId']:
  231. winVec = self.parent.FindWindowById(id)
  232. if winVec.GetName() == 'VectorFormat' and \
  233. winVec.GetSelection() != 0:
  234. native = False
  235. break
  236. # TODO: update only if needed
  237. if native:
  238. if map:
  239. self.data[win.InsertLayers] = { 'vector' : map }
  240. else:
  241. self.data[win.InsertLayers] = { }
  242. else:
  243. if map:
  244. self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
  245. else:
  246. self.data[win.InsertLayers] = { }
  247. elif name == 'TableSelect':
  248. self.data[win.InsertTables] = { 'driver' : driver,
  249. 'database' : db }
  250. elif name == 'ColumnSelect':
  251. if map:
  252. if map in cparams:
  253. if not cparams[map]['dbInfo']:
  254. cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
  255. self.data[win.InsertColumns] = { 'vector' : map, 'layer' : layer,
  256. 'dbInfo' : cparams[map]['dbInfo'] }
  257. else: # table
  258. if driver and db:
  259. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value'),
  260. 'driver' : driver,
  261. 'database' : db }
  262. elif pTable:
  263. self.data[win.InsertTableColumns] = { 'table' : pTable.get('value') }
  264. elif name == 'SubGroupSelect':
  265. pGroup = self.task.get_param('group', element = 'element', raiseError = False)
  266. if pGroup:
  267. self.data[win.Insert] = { 'group' : pGroup.get('value', '')}
  268. elif name == 'LocationSelect':
  269. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  270. if pDbase:
  271. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', '')}
  272. elif name == 'MapsetSelect':
  273. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  274. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  275. if pDbase and pLocation:
  276. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  277. 'location' : pLocation.get('value', '')}
  278. elif name == 'ProjSelect':
  279. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  280. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  281. pMapset = self.task.get_param('mapset', element = 'element', raiseError = False)
  282. if pDbase and pLocation and pMapset:
  283. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  284. 'location' : pLocation.get('value', ''),
  285. 'mapset' : pMapset.get('value', '')}
  286. def UpdateDialog(parent, event, eventId, task):
  287. return UpdateThread(parent, event, eventId, task)
  288. class UpdateQThread(Thread):
  289. """!Update dialog widgets in the thread"""
  290. requestId = 0
  291. def __init__(self, parent, requestQ, resultQ, **kwds):
  292. Thread.__init__(self, **kwds)
  293. self.parent = parent # cmdPanel
  294. self.setDaemon(True)
  295. self.requestQ = requestQ
  296. self.resultQ = resultQ
  297. self.start()
  298. def Update(self, callable, *args, **kwds):
  299. UpdateQThread.requestId += 1
  300. self.request = None
  301. self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
  302. return UpdateQThread.requestId
  303. def run(self):
  304. while True:
  305. requestId, callable, args, kwds = self.requestQ.get()
  306. requestTime = time.time()
  307. self.request = callable(*args, **kwds)
  308. self.resultQ.put((requestId, self.request.run()))
  309. if self.request:
  310. event = wxUpdateDialog(data = self.request.data)
  311. wx.PostEvent(self.parent, event)
  312. class mainFrame(wx.Frame):
  313. """!This is the Frame containing the dialog for options input.
  314. The dialog is organized in a notebook according to the guisections
  315. defined by each GRASS command.
  316. If run with a parent, it may Apply, Ok or Cancel; the latter two
  317. close the dialog. The former two trigger a callback.
  318. If run standalone, it will allow execution of the command.
  319. The command is checked and sent to the clipboard when clicking
  320. 'Copy'.
  321. """
  322. def __init__(self, parent, ID, task_description,
  323. get_dcmd = None, layer = None):
  324. self.get_dcmd = get_dcmd
  325. self.layer = layer
  326. self.task = task_description
  327. self.parent = parent # LayerTree | Modeler | None | ...
  328. if parent and parent.GetName() == 'Modeler':
  329. self.modeler = self.parent
  330. else:
  331. self.modeler = None
  332. # module name + keywords
  333. if self.task.name.split('.')[-1] in ('py', 'sh'):
  334. title = str(self.task.name.rsplit('.',1)[0])
  335. else:
  336. title = self.task.name
  337. try:
  338. if self.task.keywords != ['']:
  339. title += " [" + ', '.join(self.task.keywords) + "]"
  340. except ValueError:
  341. pass
  342. wx.Frame.__init__(self, parent = parent, id = ID, title = title,
  343. pos = wx.DefaultPosition, style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
  344. name = "MainFrame")
  345. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  346. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  347. # statusbar
  348. self.CreateStatusBar()
  349. # icon
  350. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  351. guisizer = wx.BoxSizer(wx.VERTICAL)
  352. # set apropriate output window
  353. if self.parent:
  354. self.standalone = False
  355. else:
  356. self.standalone = True
  357. # logo + description
  358. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  359. # GRASS logo
  360. self.logo = wx.StaticBitmap(parent = self.panel,
  361. bitmap = wx.Bitmap(name = os.path.join(globalvar.ETCIMGDIR,
  362. 'grass_form.png'),
  363. type = wx.BITMAP_TYPE_PNG))
  364. topsizer.Add(item = self.logo, proportion = 0, border = 3,
  365. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  366. # add module description
  367. if self.task.label:
  368. module_desc = self.task.label + ' ' + self.task.description
  369. else:
  370. module_desc = self.task.description
  371. self.description = gdialogs.StaticWrapText(parent = self.panel,
  372. label = module_desc)
  373. topsizer.Add(item = self.description, proportion = 1, border = 5,
  374. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  375. guisizer.Add(item = topsizer, proportion = 0, flag = wx.EXPAND)
  376. self.panel.SetSizerAndFit(guisizer)
  377. self.Layout()
  378. # notebooks
  379. self.notebookpanel = cmdPanel(parent = self.panel, task = self.task,
  380. mainFrame = self)
  381. self.goutput = self.notebookpanel.goutput
  382. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  383. guisizer.Add(item = self.notebookpanel, proportion = 1, flag = wx.EXPAND)
  384. # status bar
  385. status_text = _("Enter parameters for '") + self.task.name + "'"
  386. try:
  387. self.task.getCmd()
  388. self.updateValuesHook()
  389. except ValueError:
  390. self.SetStatusText(status_text)
  391. # buttons
  392. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  393. # cancel
  394. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  395. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  396. btnsizer.Add(item = self.btn_cancel, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  397. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  398. if self.get_dcmd is not None: # A callback has been set up
  399. btn_apply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  400. btn_ok = wx.Button(parent = self.panel, id = wx.ID_OK)
  401. btn_ok.SetDefault()
  402. btnsizer.Add(item = btn_apply, proportion = 0,
  403. flag = wx.ALL | wx.ALIGN_CENTER,
  404. border = 10)
  405. btnsizer.Add(item = btn_ok, proportion = 0,
  406. flag = wx.ALL | wx.ALIGN_CENTER,
  407. border = 10)
  408. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  409. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  410. else: # We're standalone
  411. # run
  412. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Run"))
  413. self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
  414. self.btn_run.SetDefault()
  415. # copy
  416. self.btn_clipboard = wx.Button(parent = self.panel, id = wx.ID_COPY, label = _("C&opy"))
  417. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
  418. btnsizer.Add(item = self.btn_run, proportion = 0,
  419. flag = wx.ALL | wx.ALIGN_CENTER,
  420. border = 10)
  421. btnsizer.Add(item = self.btn_clipboard, proportion = 0,
  422. flag = wx.ALL | wx.ALIGN_CENTER,
  423. border = 10)
  424. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  425. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  426. # help
  427. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  428. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  429. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  430. if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
  431. self.btn_help.Hide()
  432. # add help button
  433. btnsizer.Add(item = self.btn_help, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  434. guisizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  435. border = 30)
  436. if self.parent and not self.modeler:
  437. addLayer = False
  438. for p in self.task.params:
  439. if p.get('age', 'old') == 'new' and \
  440. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  441. addLayer = True
  442. if addLayer:
  443. # add newly created map into layer tree
  444. self.addbox = wx.CheckBox(parent = self.panel,
  445. label = _('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  446. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  447. guisizer.Add(item = self.addbox, proportion = 0,
  448. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  449. border = 5)
  450. hasNew = False
  451. for p in self.task.params:
  452. if p.get('age', 'old') == 'new':
  453. hasNew = True
  454. break
  455. if self.get_dcmd is None and hasNew:
  456. # close dialog when command is terminated
  457. self.closebox = wx.CheckBox(parent = self.panel,
  458. label = _('Close dialog on finish'), style = wx.NO_BORDER)
  459. self.closebox.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  460. self.closebox.SetToolTipString(_("Close dialog when command is successfully finished. "
  461. "Change this settings in Preferences dialog ('Command' tab)."))
  462. guisizer.Add(item = self.closebox, proportion = 0,
  463. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  464. border = 5)
  465. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  466. self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
  467. # do layout
  468. # called automatically by SetSizer()
  469. self.panel.SetAutoLayout(True)
  470. self.panel.SetSizerAndFit(guisizer)
  471. sizeFrame = self.GetBestSize()
  472. self.SetMinSize(sizeFrame)
  473. if hasattr(self, "closebox"):
  474. scale = 0.33
  475. else:
  476. scale = 0.50
  477. self.SetSize(wx.Size(sizeFrame[0], sizeFrame[1] + scale * max(self.notebookpanel.panelMinHeight,
  478. self.notebookpanel.constrained_size[1])))
  479. # thread to update dialog
  480. # create queues
  481. self.requestQ = Queue.Queue()
  482. self.resultQ = Queue.Queue()
  483. self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
  484. self.Layout()
  485. # keep initial window size limited for small screens
  486. width, height = self.GetSizeTuple()
  487. self.SetSize(wx.Size(min(width, 650),
  488. min(height, 500)))
  489. # fix goutput's pane size
  490. if self.goutput:
  491. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  492. def updateValuesHook(self, event = None):
  493. """!Update status bar data"""
  494. self.SetStatusText(' '.join(self.notebookpanel.createCmd(ignoreErrors = True)))
  495. if event:
  496. event.Skip()
  497. def OnKeyUp(self, event):
  498. """!Key released (check hot-keys)"""
  499. try:
  500. kc = chr(event.GetKeyCode())
  501. except ValueError:
  502. event.Skip()
  503. return
  504. if not event.ControlDown():
  505. event.Skip()
  506. return
  507. if kc == 'Q':
  508. self.OnCancel(None)
  509. elif kc == 'S':
  510. self.OnAbort(None)
  511. elif kc == 'H':
  512. self.OnHelp(None)
  513. elif kc == 'R':
  514. self.OnRun(None)
  515. elif kc == 'C':
  516. self.OnCopy(None)
  517. event.Skip()
  518. def OnDone(self, cmd, returncode):
  519. """!This function is launched from OnRun() when command is
  520. finished
  521. @param returncode command's return code (0 for success)
  522. """
  523. if not self.parent or returncode != 0:
  524. return
  525. if self.parent.GetName() not in ('LayerTree', 'LayerManager'):
  526. return
  527. if self.parent.GetName() == 'LayerTree':
  528. display = self.parent.GetMapDisplay()
  529. else: # Layer Manager
  530. display = self.parent.GetLayerTree().GetMapDisplay()
  531. if not display or not display.IsAutoRendered():
  532. return
  533. mapLayers = map(lambda x: x.GetName(),
  534. display.GetRender().GetListOfLayers(l_type = 'raster') +
  535. display.GetRender().GetListOfLayers(l_type = 'vector'))
  536. task = GUI(show = None).ParseCommand(cmd)
  537. for p in task.get_options()['params']:
  538. if p.get('prompt', '') not in ('raster', 'vector'):
  539. continue
  540. mapName = p.get('value', '')
  541. if '@' not in mapName:
  542. mapName = mapName + '@' + grass.gisenv()['MAPSET']
  543. if mapName in mapLayers:
  544. display.GetWindow().UpdateMap(render = True)
  545. return
  546. def OnOK(self, event):
  547. """!OK button pressed"""
  548. cmd = self.OnApply(event)
  549. if cmd is not None and self.get_dcmd is not None:
  550. self.OnCancel(event)
  551. def OnApply(self, event):
  552. """!Apply the command"""
  553. if self.modeler:
  554. cmd = self.createCmd(ignoreErrors = True, ignoreRequired = True)
  555. else:
  556. cmd = self.createCmd()
  557. if cmd is not None and self.get_dcmd is not None:
  558. # return d.* command to layer tree for rendering
  559. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  560. "flags" : self.task.flags},
  561. self)
  562. # echo d.* command to output console
  563. # self.parent.writeDCommand(cmd)
  564. return cmd
  565. def OnRun(self, event):
  566. """!Run the command"""
  567. cmd = self.createCmd()
  568. if not cmd or len(cmd) < 1:
  569. return
  570. if self.standalone or cmd[0][0:2] != "d.":
  571. # Send any non-display command to parent window (probably wxgui.py)
  572. # put to parents switch to 'Command output'
  573. self.notebookpanel.notebook.SetSelectionByName('output')
  574. try:
  575. if self.task.path:
  576. cmd[0] = self.task.path # full path
  577. self.goutput.RunCmd(cmd, onDone = self.OnDone)
  578. except AttributeError, e:
  579. print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (e)
  580. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  581. else:
  582. gcmd.Command(cmd)
  583. # update buttons status
  584. for btn in (self.btn_run,
  585. self.btn_cancel,
  586. self.btn_clipboard,
  587. self.btn_help):
  588. btn.Enable(False)
  589. def OnAbort(self, event):
  590. """!Abort running command"""
  591. event = goutput.wxCmdAbort(aborted = True)
  592. wx.PostEvent(self.goutput, event)
  593. def OnCopy(self, event):
  594. """!Copy the command"""
  595. cmddata = wx.TextDataObject()
  596. # list -> string
  597. cmdstring = ' '.join(self.createCmd(ignoreErrors = True))
  598. cmddata.SetText(cmdstring)
  599. if wx.TheClipboard.Open():
  600. # wx.TheClipboard.UsePrimarySelection(True)
  601. wx.TheClipboard.SetData(cmddata)
  602. wx.TheClipboard.Close()
  603. self.SetStatusText(_("'%s' copied to clipboard") % \
  604. (cmdstring))
  605. def OnCancel(self, event):
  606. """!Cancel button pressed"""
  607. self.MakeModal(False)
  608. if self.get_dcmd and \
  609. self.parent and \
  610. self.parent.GetName() in ('LayerTree',
  611. 'MapWindow'):
  612. # display decorations and
  613. # pressing OK or cancel after setting layer properties
  614. if self.task.name in ['d.barscale','d.legend','d.histogram'] \
  615. or len(self.parent.GetPyData(self.layer)[0]['cmd']) >= 1:
  616. self.Hide()
  617. # canceled layer with nothing set
  618. elif len(self.parent.GetPyData(self.layer)[0]['cmd']) < 1:
  619. self.parent.Delete(self.layer)
  620. self.Destroy()
  621. else:
  622. # cancel for non-display commands
  623. self.Destroy()
  624. def OnHelp(self, event):
  625. """!Show manual page (switch to the 'Manual' notebook page)"""
  626. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  627. self.notebookpanel.notebook.SetSelectionByName('manual')
  628. self.notebookpanel.OnPageChange(None)
  629. if event:
  630. event.Skip()
  631. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  632. """!Create command string (python list)"""
  633. return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors,
  634. ignoreRequired = ignoreRequired)
  635. class cmdPanel(wx.Panel):
  636. """!A panel containing a notebook dividing in tabs the different
  637. guisections of the GRASS cmd.
  638. """
  639. def __init__(self, parent, task, id = wx.ID_ANY, mainFrame = None, *args, **kwargs):
  640. if mainFrame:
  641. self.parent = mainFrame
  642. else:
  643. self.parent = parent
  644. self.task = task
  645. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  646. # Determine tab layout
  647. sections = []
  648. is_section = {}
  649. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  650. self.label_id = [] # wrap titles on resize
  651. self.Bind(wx.EVT_SIZE, self.OnSize)
  652. for task in not_hidden:
  653. if task.get('required', False):
  654. # All required go into Main, even if they had defined another guisection
  655. task['guisection'] = _('Required')
  656. if task.get('guisection','') == '':
  657. # Undefined guisections end up into Options
  658. task['guisection'] = _('Optional')
  659. if task['guisection'] not in is_section:
  660. # We do it like this to keep the original order, except for Main which goes first
  661. is_section[task['guisection']] = 1
  662. sections.append(task['guisection'])
  663. else:
  664. is_section[ task['guisection'] ] += 1
  665. del is_section
  666. # 'Required' tab goes first, 'Optional' as the last one
  667. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  668. if content in sections:
  669. idx = sections.index(content)
  670. sections[idx:idx+1] = []
  671. sections[newidx:newidx] = [content]
  672. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  673. # Build notebook
  674. self.notebook = GNotebook(self, style = globalvar.FNPageStyle)
  675. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  676. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  677. tab = {}
  678. tabsizer = {}
  679. for section in sections:
  680. tab[section] = scrolled.ScrolledPanel(parent = self.notebook)
  681. tab[section].SetScrollRate(10, 10)
  682. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  683. self.notebook.AddPage(page = tab[section], text = section)
  684. # are we running from command line?
  685. ### add 'command output' tab regardless standalone dialog
  686. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  687. self.goutput = goutput.GMConsole(parent = self, margin = False)
  688. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  689. else:
  690. self.goutput = None
  691. self.manual_tab = HelpPanel(parent = self, grass_command = self.task.name)
  692. if not self.manual_tab.IsFile():
  693. self.manual_tab.Hide()
  694. else:
  695. self.notebook.AddPage(page = self.manual_tab, text = _("Manual"), name = 'manual')
  696. self.notebook.SetSelection(0)
  697. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  698. #
  699. # flags
  700. #
  701. text_style = wx.FONTWEIGHT_NORMAL
  702. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  703. for f in visible_flags:
  704. which_sizer = tabsizer[ f['guisection'] ]
  705. which_panel = tab[ f['guisection'] ]
  706. # if label is given: description -> tooltip
  707. if f.get('label','') != '':
  708. title = text_beautify(f['label'])
  709. tooltip = text_beautify(f['description'], width = -1)
  710. else:
  711. title = text_beautify(f['description'])
  712. tooltip = None
  713. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  714. rtitle_txt = wx.StaticText(parent = which_panel,
  715. label = '(' + f['name'] + ')')
  716. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  717. self.label_id.append(chk.GetId())
  718. if tooltip:
  719. chk.SetToolTipString(tooltip)
  720. chk.SetValue(f.get('value', False))
  721. title_sizer.Add(item = chk, proportion = 1,
  722. flag = wx.EXPAND)
  723. title_sizer.Add(item = rtitle_txt, proportion = 0,
  724. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  725. which_sizer.Add(item = title_sizer, proportion = 0,
  726. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  727. f['wxId'] = [ chk.GetId(), ]
  728. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  729. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  730. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  731. label = _("Parameterized in model"))
  732. parChk.SetName('ModelParam')
  733. parChk.SetValue(f.get('parameterized', False))
  734. if 'wxId' in f:
  735. f['wxId'].append(parChk.GetId())
  736. else:
  737. f['wxId'] = [ parChk.GetId() ]
  738. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  739. which_sizer.Add(item = parChk, proportion = 0,
  740. flag = wx.LEFT, border = 20)
  741. if f['name'] in ('verbose', 'quiet'):
  742. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  743. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  744. if f['name'] == vq:
  745. chk.SetValue(True)
  746. f['value'] = True
  747. elif f['name'] == 'overwrite' and 'value' not in f:
  748. chk.SetValue(UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled'))
  749. f['value'] = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  750. #
  751. # parameters
  752. #
  753. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  754. try:
  755. first_param = visible_params[0]
  756. except IndexError:
  757. first_param = None
  758. for p in visible_params:
  759. which_sizer = tabsizer[ p['guisection'] ]
  760. which_panel = tab[ p['guisection'] ]
  761. # if label is given -> label and description -> tooltip
  762. # otherwise description -> lavel
  763. if p.get('label','') != '':
  764. title = text_beautify(p['label'])
  765. tooltip = text_beautify(p['description'], width = -1)
  766. else:
  767. title = text_beautify(p['description'])
  768. tooltip = None
  769. txt = None
  770. # text style (required -> bold)
  771. if not p.get('required', False):
  772. text_style = wx.FONTWEIGHT_NORMAL
  773. else:
  774. text_style = wx.FONTWEIGHT_BOLD
  775. # title sizer (description, name, type)
  776. if (len(p.get('values', [])) > 0) and \
  777. p.get('multiple', False) and \
  778. p.get('gisprompt',False) == False and \
  779. p.get('type', '') == 'string':
  780. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  781. else:
  782. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  783. title_txt = wx.StaticText(parent = which_panel)
  784. if p['key_desc']:
  785. ltype = ','.join(p['key_desc'])
  786. else:
  787. ltype = p['type']
  788. rtitle_txt = wx.StaticText(parent = which_panel,
  789. label = '(' + p['name'] + '=' + ltype + ')')
  790. title_sizer.Add(item = title_txt, proportion = 1,
  791. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  792. title_sizer.Add(item = rtitle_txt, proportion = 0,
  793. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  794. which_sizer.Add(item = title_sizer, proportion = 0,
  795. flag = wx.EXPAND)
  796. self.label_id.append(title_txt.GetId())
  797. # title expansion
  798. if p.get('multiple', False) and len(p.get('values','')) == 0:
  799. title = _("[multiple]") + " " + title
  800. if p.get('value','') == '' :
  801. p['value'] = p.get('default','')
  802. if (len(p.get('values', [])) > 0):
  803. valuelist = map(str, p.get('values',[]))
  804. valuelist_desc = map(unicode, p.get('values_desc',[]))
  805. if p.get('multiple', False) and \
  806. p.get('gisprompt',False) == False and \
  807. p.get('type', '') == 'string':
  808. title_txt.SetLabel(" %s: (%s, %s) " % (title, p['name'], p['type']))
  809. if valuelist_desc:
  810. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  811. else:
  812. hSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.HORIZONTAL)
  813. isEnabled = {}
  814. # copy default values
  815. if p['value'] == '':
  816. p['value'] = p.get('default', '')
  817. for defval in p.get('value', '').split(','):
  818. isEnabled[ defval ] = 'yes'
  819. # for multi checkboxes, this is an array of all wx IDs
  820. # for each individual checkbox
  821. p[ 'wxId' ] = list()
  822. idx = 0
  823. for val in valuelist:
  824. try:
  825. label = valuelist_desc[idx]
  826. except IndexError:
  827. label = val
  828. chkbox = wx.CheckBox(parent = which_panel,
  829. label = text_beautify(label))
  830. p[ 'wxId' ].append(chkbox.GetId())
  831. if val in isEnabled:
  832. chkbox.SetValue(True)
  833. hSizer.Add(item = chkbox, proportion = 0,
  834. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  835. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  836. idx += 1
  837. which_sizer.Add(item = hSizer, proportion = 0,
  838. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  839. elif p.get('gisprompt', False) == False:
  840. if len(valuelist) == 1: # -> textctrl
  841. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  842. str(valuelist[0])))
  843. if p.get('type', '') == 'integer' and \
  844. not p.get('multiple', False):
  845. # for multiple integers use textctrl instead of spinsctrl
  846. try:
  847. minValue, maxValue = map(int, valuelist[0].split('-'))
  848. except ValueError:
  849. minValue = -1e6
  850. maxValue = 1e6
  851. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  852. min = minValue, max = maxValue)
  853. txt2.SetName("SpinCtrl")
  854. style = wx.BOTTOM | wx.LEFT
  855. else:
  856. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  857. txt2.SetName("TextCtrl")
  858. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  859. value = self._getValue(p)
  860. # parameter previously set
  861. if value:
  862. if txt2.GetName() == "SpinCtrl":
  863. txt2.SetValue(int(value))
  864. else:
  865. txt2.SetValue(value)
  866. which_sizer.Add(item = txt2, proportion = 0,
  867. flag = style, border = 5)
  868. p['wxId'] = [ txt2.GetId(), ]
  869. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  870. else:
  871. # list of values (combo)
  872. title_txt.SetLabel(title + ':')
  873. cb = wx.ComboBox(parent = which_panel, id = wx.ID_ANY, value = p.get('default',''),
  874. size = globalvar.DIALOG_COMBOBOX_SIZE,
  875. choices = valuelist, style = wx.CB_DROPDOWN)
  876. value = self._getValue(p)
  877. if value:
  878. cb.SetValue(value) # parameter previously set
  879. which_sizer.Add(item = cb, proportion = 0,
  880. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  881. p['wxId'] = [cb.GetId(),]
  882. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  883. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  884. # text entry
  885. if (p.get('type','string') in ('string','integer','float')
  886. and len(p.get('values',[])) == 0
  887. and p.get('gisprompt',False) == False
  888. and p.get('prompt','') != 'color'):
  889. title_txt.SetLabel(title + ':')
  890. if p.get('multiple', False) or \
  891. p.get('type', 'string') == 'string' or \
  892. len(p.get('key_desc', [])) > 1:
  893. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  894. value = self._getValue(p)
  895. if value:
  896. # parameter previously set
  897. txt3.SetValue(str(value))
  898. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  899. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  900. else:
  901. minValue = -1e9
  902. maxValue = 1e9
  903. if p.get('type', '') == 'integer':
  904. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default',''),
  905. size = globalvar.DIALOG_SPIN_SIZE,
  906. min = minValue, max = maxValue)
  907. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  908. value = self._getValue(p)
  909. if value:
  910. txt3.SetValue(int(value)) # parameter previously set
  911. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  912. else:
  913. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  914. validator = FloatValidator())
  915. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  916. value = self._getValue(p)
  917. if value:
  918. txt3.SetValue(str(value)) # parameter previously set
  919. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  920. which_sizer.Add(item = txt3, proportion = 0,
  921. flag = style, border = 5)
  922. p['wxId'] = [ txt3.GetId(), ]
  923. #
  924. # element selection tree combobox (maps, icons, regions, etc.)
  925. #
  926. if p.get('gisprompt', False) == True:
  927. title_txt.SetLabel(title + ':')
  928. # GIS element entry
  929. if p.get('prompt','') not in ('color',
  930. 'color_none',
  931. 'subgroup',
  932. 'dbdriver',
  933. 'dbname',
  934. 'dbtable',
  935. 'dbcolumn',
  936. 'layer',
  937. 'layer_all',
  938. 'location',
  939. 'mapset',
  940. 'dbase') and \
  941. p.get('element', '') != 'file':
  942. multiple = p.get('multiple', False)
  943. if p.get('age', '') == 'new':
  944. mapsets = [grass.gisenv()['MAPSET'],]
  945. else:
  946. mapsets = None
  947. if self.task.name in ('r.proj', 'v.proj') \
  948. and p.get('name', '') == 'input':
  949. if self.task.name == 'r.proj':
  950. isRaster = True
  951. else:
  952. isRaster = False
  953. selection = gselect.ProjSelect(parent = which_panel,
  954. isRaster = isRaster)
  955. p['wxId'] = [ selection.GetId(), ]
  956. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  957. formatSelector = False
  958. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  959. else:
  960. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  961. size = globalvar.DIALOG_GSELECT_SIZE,
  962. type = p.get('element', ''),
  963. multiple = multiple, mapsets = mapsets)
  964. value = self._getValue(p)
  965. if value:
  966. selection.SetValue(value)
  967. formatSelector = True
  968. # A select.Select is a combobox with two children: a textctl and a popupwindow;
  969. # we target the textctl here
  970. textWin = selection.GetTextCtrl()
  971. p['wxId'] = [ textWin.GetId(), ]
  972. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  973. if p.get('prompt', '') == 'vector':
  974. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  975. if formatSelector and p.get('age', 'old') == 'old':
  976. # OGR supported (read-only)
  977. self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  978. self.hsizer.Add(item = selection,
  979. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  980. border = 5)
  981. # format (native / ogr)
  982. rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  983. label = " %s " % _("Format"),
  984. style = wx.RA_SPECIFY_ROWS,
  985. choices = [_("Native / Linked OGR"), _("Direct OGR")])
  986. if p.get('value', '').lower().rfind('@ogr') > -1:
  987. rbox.SetSelection(1)
  988. rbox.SetName('VectorFormat')
  989. rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  990. self.hsizer.Add(item = rbox,
  991. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  992. wx.RIGHT | wx.ALIGN_TOP,
  993. border = 5)
  994. ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  995. default = 'dir',
  996. exclude = ['file'])
  997. self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  998. self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  999. ogrSelection.SetName('OgrSelect')
  1000. ogrSelection.Hide()
  1001. which_sizer.Add(item = self.hsizer, proportion = 0)
  1002. p['wxId'].append(rbox.GetId())
  1003. p['wxId'].append(ogrSelection.GetId())
  1004. for win in ogrSelection.GetDsnWin():
  1005. p['wxId'].append(win.GetId())
  1006. else:
  1007. which_sizer.Add(item = selection, proportion = 0,
  1008. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1009. border = 5)
  1010. elif p.get('prompt', '') == 'group':
  1011. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1012. which_sizer.Add(item = selection, proportion = 0,
  1013. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1014. border = 5)
  1015. else:
  1016. which_sizer.Add(item = selection, proportion = 0,
  1017. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1018. border = 5)
  1019. # subgroup
  1020. elif p.get('prompt', '') == 'subgroup':
  1021. selection = gselect.SubGroupSelect(parent = which_panel)
  1022. p['wxId'] = [ selection.GetId() ]
  1023. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1024. which_sizer.Add(item = selection, proportion = 0,
  1025. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1026. border = 5)
  1027. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1028. elif p.get('prompt', '') in ('dbdriver',
  1029. 'dbname',
  1030. 'dbtable',
  1031. 'dbcolumn',
  1032. 'layer',
  1033. 'layer_all',
  1034. 'location',
  1035. 'mapset',
  1036. 'dbase'):
  1037. if p.get('multiple', 'no') == 'yes':
  1038. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1039. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1040. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1041. else:
  1042. value = self._getValue(p)
  1043. if p.get('prompt', '') in ('layer',
  1044. 'layer_all'):
  1045. if p.get('prompt', '') == 'layer_all':
  1046. all = True
  1047. else:
  1048. all = False
  1049. if p.get('age', 'old') == 'old':
  1050. win = gselect.LayerSelect(parent = which_panel,
  1051. all = all,
  1052. default = p['default'])
  1053. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1054. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1055. win.SetValue(str(value)) # default or previously set value
  1056. else:
  1057. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1058. min = 1, max = 100, initial = int(p['default']))
  1059. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1060. win.SetValue(int(value)) # default or previously set value
  1061. p['wxId'] = [ win.GetId() ]
  1062. elif p.get('prompt', '') == 'dbdriver':
  1063. win = gselect.DriverSelect(parent = which_panel,
  1064. choices = p.get('values', []),
  1065. value = value)
  1066. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1067. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1068. elif p.get('prompt', '') == 'dbname':
  1069. win = gselect.DatabaseSelect(parent = which_panel,
  1070. value = value)
  1071. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1072. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1073. elif p.get('prompt', '') == 'dbtable':
  1074. if p.get('age', 'old') == 'old':
  1075. win = gselect.TableSelect(parent = which_panel)
  1076. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1077. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1078. else:
  1079. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1080. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1081. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1082. elif p.get('prompt', '') == 'dbcolumn':
  1083. win = gselect.ColumnSelect(parent = which_panel,
  1084. value = value,
  1085. param = p)
  1086. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1087. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1088. elif p.get('prompt', '') == 'location':
  1089. win = gselect.LocationSelect(parent = which_panel,
  1090. value = value)
  1091. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1092. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1093. elif p.get('prompt', '') == 'mapset':
  1094. win = gselect.MapsetSelect(parent = which_panel,
  1095. value = value)
  1096. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1097. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1098. elif p.get('prompt', '') == 'dbase':
  1099. win = gselect.DbaseSelect(parent = which_panel,
  1100. changeCallback = self.OnSetValue)
  1101. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1102. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1103. if 'wxId' not in p:
  1104. try:
  1105. p['wxId'] = [ win.GetId(), ]
  1106. except AttributeError:
  1107. pass
  1108. which_sizer.Add(item = win, proportion = 0,
  1109. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1110. # color entry
  1111. elif p.get('prompt', '') in ('color',
  1112. 'color_none'):
  1113. default_color = (200,200,200)
  1114. label_color = _("Select Color")
  1115. if p.get('default','') != '':
  1116. default_color, label_color = color_resolve(p['default'])
  1117. if p.get('value','') != '': # parameter previously set
  1118. default_color, label_color = color_resolve(p['value'])
  1119. if p.get('prompt', '') == 'color_none':
  1120. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1121. else:
  1122. this_sizer = which_sizer
  1123. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1124. label = label_color, colour = default_color,
  1125. pos = wx.DefaultPosition, size = (150,-1))
  1126. this_sizer.Add(item = btn_colour, proportion = 0,
  1127. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1128. # For color selectors, this is a two-member array, holding the IDs of
  1129. # the selector proper and either a "transparent" button or None
  1130. p['wxId'] = [btn_colour.GetId(),]
  1131. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1132. if p.get('prompt', '') == 'color_none':
  1133. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1134. if p.get('value','') != '' and p.get('value',[''])[0] == "none":
  1135. none_check.SetValue(True)
  1136. else:
  1137. none_check.SetValue(False)
  1138. this_sizer.Add(item = none_check, proportion = 0,
  1139. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1140. which_sizer.Add(this_sizer)
  1141. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1142. p['wxId'].append(none_check.GetId())
  1143. else:
  1144. p['wxId'].append(None)
  1145. # file selector
  1146. elif p.get('prompt','') != 'color' and p.get('element', '') == 'file':
  1147. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = '*',
  1148. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1149. dialogTitle = _('Choose %s') % \
  1150. p.get('description',_('File')),
  1151. buttonText = _('Browse'),
  1152. startDirectory = os.getcwd(), fileMode = 0,
  1153. changeCallback = self.OnSetValue)
  1154. value = self._getValue(p)
  1155. if value:
  1156. fbb.SetValue(value) # parameter previously set
  1157. which_sizer.Add(item = fbb, proportion = 0,
  1158. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1159. # A file browse button is a combobox with two children:
  1160. # a textctl and a button;
  1161. # we have to target the button here
  1162. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1163. if p.get('age', 'new') == 'old' and \
  1164. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1165. # widget for interactive input
  1166. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1167. style = wx.TE_MULTILINE,
  1168. size = (-1, 75))
  1169. if p.get('value', '') and os.path.isfile(p['value']):
  1170. f = open(p['value'])
  1171. ifbb.SetValue(''.join(f.readlines()))
  1172. f.close()
  1173. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1174. which_sizer.Add(item = wx.StaticText(parent = which_panel, id = wx.ID_ANY,
  1175. label = _('or enter values interactively')),
  1176. proportion = 0,
  1177. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1178. which_sizer.Add(item = ifbb, proportion = 1,
  1179. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1180. p['wxId'].append(ifbb.GetId())
  1181. if self.parent.GetName() == 'MainFrame' and self.parent.modeler:
  1182. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1183. label = _("Parameterized in model"))
  1184. parChk.SetName('ModelParam')
  1185. parChk.SetValue(p.get('parameterized', False))
  1186. if 'wxId' in p:
  1187. p['wxId'].append(parChk.GetId())
  1188. else:
  1189. p['wxId'] = [ parChk.GetId() ]
  1190. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1191. which_sizer.Add(item = parChk, proportion = 0,
  1192. flag = wx.LEFT, border = 20)
  1193. if title_txt is not None:
  1194. # create tooltip if given
  1195. if len(p['values_desc']) > 0:
  1196. if tooltip:
  1197. tooltip += 2 * os.linesep
  1198. else:
  1199. tooltip = ''
  1200. if len(p['values']) == len(p['values_desc']):
  1201. for i in range(len(p['values'])):
  1202. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1203. tooltip.strip(os.linesep)
  1204. if tooltip:
  1205. title_txt.SetToolTipString(tooltip)
  1206. if p == first_param:
  1207. if 'wxId' in p and len(p['wxId']) > 0:
  1208. win = self.FindWindowById(p['wxId'][0])
  1209. win.SetFocus()
  1210. #
  1211. # set widget relations for OnUpdateSelection
  1212. #
  1213. pMap = None
  1214. pLayer = []
  1215. pDriver = None
  1216. pDatabase = None
  1217. pTable = None
  1218. pColumn = []
  1219. pGroup = None
  1220. pSubGroup = None
  1221. pDbase = None
  1222. pLocation = None
  1223. pMapset = None
  1224. for p in self.task.params:
  1225. if p.get('gisprompt', False) == False:
  1226. continue
  1227. guidep = p.get('guidependency', '')
  1228. if guidep:
  1229. # fixed options dependency defined
  1230. options = guidep.split(',')
  1231. for opt in options:
  1232. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1233. if id:
  1234. if 'wxId-bind' not in p:
  1235. p['wxId-bind'] = list()
  1236. p['wxId-bind'] += pOpt['wxId']
  1237. continue
  1238. prompt = p.get('element', '')
  1239. if prompt in ('cell', 'vector'):
  1240. name = p.get('name', '')
  1241. if name in ('map', 'input'):
  1242. pMap = p
  1243. elif prompt == 'layer':
  1244. pLayer.append(p)
  1245. elif prompt == 'dbcolumn':
  1246. pColumn.append(p)
  1247. elif prompt == 'dbdriver':
  1248. pDriver = p
  1249. elif prompt == 'dbname':
  1250. pDatabase = p
  1251. elif prompt == 'dbtable':
  1252. pTable = p
  1253. elif prompt == 'group':
  1254. pGroup = p
  1255. elif prompt == 'subgroup':
  1256. pSubGroup = p
  1257. elif prompt == 'dbase':
  1258. pDbase = p
  1259. elif prompt == 'location':
  1260. pLocation = p
  1261. elif prompt == 'mapset':
  1262. pMapset = p
  1263. # collect ids
  1264. pColumnIds = []
  1265. for p in pColumn:
  1266. pColumnIds += p['wxId']
  1267. pLayerIds = []
  1268. for p in pLayer:
  1269. pLayerIds += p['wxId']
  1270. # set wxId-bindings
  1271. if pMap:
  1272. pMap['wxId-bind'] = copy.copy(pColumnIds)
  1273. if pLayer:
  1274. pMap['wxId-bind'] += pLayerIds
  1275. if pLayer:
  1276. for p in pLayer:
  1277. p['wxId-bind'] = copy.copy(pColumnIds)
  1278. if pDriver and pTable:
  1279. pDriver['wxId-bind'] = pTable['wxId']
  1280. if pDatabase and pTable:
  1281. pDatabase['wxId-bind'] = pTable['wxId']
  1282. if pTable and pColumnIds:
  1283. pTable['wxId-bind'] = pColumnIds
  1284. if pGroup and pSubGroup:
  1285. pGroup['wxId-bind'] = pSubGroup['wxId']
  1286. if pDbase and pLocation:
  1287. pDbase['wxId-bind'] = pLocation['wxId']
  1288. if pLocation and pMapset:
  1289. pLocation['wxId-bind'] = pMapset['wxId']
  1290. if pLocation and pMapset and pMap:
  1291. pLocation['wxId-bind'] += pMap['wxId']
  1292. pMapset['wxId-bind'] = pMap['wxId']
  1293. #
  1294. # determine panel size
  1295. #
  1296. maxsizes = (0, 0)
  1297. for section in sections:
  1298. tab[section].SetSizer(tabsizer[section])
  1299. tabsizer[section].Fit(tab[section])
  1300. tab[section].Layout()
  1301. minsecsizes = tabsizer[section].GetSize()
  1302. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1303. # TODO: be less arbitrary with these 600
  1304. self.panelMinHeight = 100
  1305. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1306. for section in sections:
  1307. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1308. if self.manual_tab.IsLoaded():
  1309. self.manual_tab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1310. self.SetSizer(panelsizer)
  1311. panelsizer.Fit(self.notebook)
  1312. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1313. def _getValue(self, p):
  1314. """!Get value or default value of given parameter
  1315. @param p parameter directory
  1316. """
  1317. if p.get('value', '') != '':
  1318. return p['value']
  1319. return p.get('default', '')
  1320. def OnFileText(self, event):
  1321. """File input interactively entered"""
  1322. text = event.GetString()
  1323. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1324. if not p:
  1325. return # should not happen
  1326. win = self.FindWindowById(p['wxId'][0])
  1327. if text:
  1328. filename = win.GetValue()
  1329. if not filename:
  1330. # outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
  1331. filename = grass.tempfile()
  1332. win.SetValue(filename)
  1333. f = open(filename, "w")
  1334. try:
  1335. f.write(text)
  1336. finally:
  1337. f.close()
  1338. else:
  1339. win.SetValue('')
  1340. def OnVectorFormat(self, event):
  1341. """!Change vector format (native / ogr)"""
  1342. sel = event.GetSelection()
  1343. idEvent = event.GetId()
  1344. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1345. if not p:
  1346. return # should not happen
  1347. # detect windows
  1348. winNative = None
  1349. winOgr = None
  1350. for id in p['wxId']:
  1351. if id == idEvent:
  1352. continue
  1353. name = self.FindWindowById(id).GetName()
  1354. if name == 'Select':
  1355. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1356. elif name == 'OgrSelect':
  1357. winOgr = self.FindWindowById(id)
  1358. # enable / disable widgets & update values
  1359. rbox = self.FindWindowByName('VectorFormat')
  1360. self.hsizer.Remove(rbox)
  1361. if sel == 0: # -> native
  1362. winOgr.Hide()
  1363. self.hsizer.Remove(winOgr)
  1364. self.hsizer.Add(item = winNative,
  1365. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1366. border = 5)
  1367. winNative.Show()
  1368. p['value'] = winNative.GetValue()
  1369. elif sel == 1: # -> OGR
  1370. sizer = wx.BoxSizer(wx.VERTICAL)
  1371. winNative.Hide()
  1372. self.hsizer.Remove(winNative)
  1373. sizer.Add(item = winOgr)
  1374. winOgr.Show()
  1375. p['value'] = winOgr.GetDsn()
  1376. self.hsizer.Add(item = sizer,
  1377. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1378. border = 5)
  1379. self.hsizer.Add(item = rbox,
  1380. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1381. wx.RIGHT | wx.ALIGN_TOP,
  1382. border = 5)
  1383. self.hsizer.Layout()
  1384. self.Layout()
  1385. self.OnUpdateValues()
  1386. self.OnUpdateSelection(event)
  1387. def OnUpdateDialog(self, event):
  1388. for fn, kwargs in event.data.iteritems():
  1389. fn(**kwargs)
  1390. self.parent.updateValuesHook()
  1391. def OnVerbosity(self, event):
  1392. """!Verbosity level changed"""
  1393. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1394. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1395. if event.IsChecked():
  1396. if event.GetId() == verbose.GetId():
  1397. if quiet.IsChecked():
  1398. quiet.SetValue(False)
  1399. self.task.get_flag('quiet')['value'] = False
  1400. else:
  1401. if verbose.IsChecked():
  1402. verbose.SetValue(False)
  1403. self.task.get_flag('verbose')['value'] = False
  1404. event.Skip()
  1405. def OnPageChange(self, event):
  1406. if not event:
  1407. sel = self.notebook.GetSelection()
  1408. else:
  1409. sel = event.GetSelection()
  1410. idx = self.notebook.GetPageIndexByName('manual')
  1411. if idx > -1 and sel == idx:
  1412. # calling LoadPage() is strangely time-consuming (only first call)
  1413. # FIXME: move to helpPage.__init__()
  1414. if not self.manual_tab.IsLoaded():
  1415. wx.Yield()
  1416. self.manual_tab.LoadPage()
  1417. self.Layout()
  1418. def OnColorChange(self, event):
  1419. myId = event.GetId()
  1420. for p in self.task.params:
  1421. if 'wxId' in p and myId in p['wxId']:
  1422. has_button = p['wxId'][1] is not None
  1423. if has_button and wx.FindWindowById(p['wxId'][1]).GetValue() == True:
  1424. p[ 'value' ] = 'none'
  1425. else:
  1426. colorchooser = wx.FindWindowById(p['wxId'][0])
  1427. new_color = colorchooser.GetValue()[:]
  1428. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1429. # under wx2.8.1
  1430. new_label = rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1431. colorchooser.SetLabel(new_label)
  1432. colorchooser.SetColour(new_color)
  1433. colorchooser.Refresh()
  1434. p[ 'value' ] = colorchooser.GetLabel()
  1435. self.OnUpdateValues()
  1436. def OnUpdateValues(self, event = None):
  1437. """!If we were part of a richer interface, report back the
  1438. current command being built.
  1439. This method should be set by the parent of this panel if
  1440. needed. It's a hook, actually. Beware of what is 'self' in
  1441. the method def, though. It will be called with no arguments.
  1442. """
  1443. pass
  1444. def OnCheckBoxMulti(self, event):
  1445. """!Fill the values as a ','-separated string according to
  1446. current status of the checkboxes.
  1447. """
  1448. me = event.GetId()
  1449. theParam = None
  1450. for p in self.task.params:
  1451. if 'wxId' in p and me in p['wxId']:
  1452. theParam = p
  1453. myIndex = p['wxId'].index(me)
  1454. # Unpack current value list
  1455. currentValues = {}
  1456. for isThere in theParam.get('value', '').split(','):
  1457. currentValues[isThere] = 1
  1458. theValue = theParam['values'][myIndex]
  1459. if event.Checked():
  1460. currentValues[ theValue ] = 1
  1461. else:
  1462. del currentValues[ theValue ]
  1463. # Keep the original order, so that some defaults may be recovered
  1464. currentValueList = []
  1465. for v in theParam['values']:
  1466. if v in currentValues:
  1467. currentValueList.append(v)
  1468. # Pack it back
  1469. theParam['value'] = ','.join(currentValueList)
  1470. self.OnUpdateValues()
  1471. def OnSetValue(self, event):
  1472. """!Retrieve the widget value and set the task value field
  1473. accordingly.
  1474. Use for widgets that have a proper GetValue() method, i.e. not
  1475. for selectors.
  1476. """
  1477. myId = event.GetId()
  1478. me = wx.FindWindowById(myId)
  1479. name = me.GetName()
  1480. found = False
  1481. for porf in self.task.params + self.task.flags:
  1482. if 'wxId' not in porf:
  1483. continue
  1484. if myId in porf['wxId']:
  1485. found = True
  1486. break
  1487. if not found:
  1488. return
  1489. if name in ('DriverSelect', 'TableSelect',
  1490. 'LocationSelect', 'MapsetSelect', 'ProjSelect'):
  1491. porf['value'] = me.GetStringSelection()
  1492. elif name == 'GdalSelect':
  1493. porf['value'] = event.dsn
  1494. elif name == 'ModelParam':
  1495. porf['parameterized'] = me.IsChecked()
  1496. elif name == 'LayerSelect':
  1497. porf['value'] = me.GetValue()
  1498. else:
  1499. porf['value'] = me.GetValue()
  1500. self.OnUpdateValues(event)
  1501. event.Skip()
  1502. def OnUpdateSelection(self, event):
  1503. """!Update dialog (layers, tables, columns, etc.)
  1504. """
  1505. if not hasattr(self.parent, "updateThread"):
  1506. if event:
  1507. event.Skip()
  1508. return
  1509. if event:
  1510. self.parent.updateThread.Update(UpdateDialog,
  1511. self,
  1512. event,
  1513. event.GetId(),
  1514. self.task)
  1515. else:
  1516. self.parent.updateThread.Update(UpdateDialog,
  1517. self,
  1518. None,
  1519. None,
  1520. self.task)
  1521. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1522. """!Produce a command line string (list) or feeding into GRASS.
  1523. @param ignoreErrors True then it will return whatever has been
  1524. built so far, even though it would not be a correct command
  1525. for GRASS
  1526. """
  1527. try:
  1528. cmd = self.task.getCmd(ignoreErrors = ignoreErrors,
  1529. ignoreRequired = ignoreRequired)
  1530. except ValueError, err:
  1531. dlg = wx.MessageDialog(parent = self,
  1532. message = unicode(err),
  1533. caption = _("Error in %s") % self.task.name,
  1534. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1535. dlg.ShowModal()
  1536. dlg.Destroy()
  1537. cmd = None
  1538. return cmd
  1539. def OnSize(self, event):
  1540. width = event.GetSize()[0]
  1541. fontsize = self.GetFont().GetPointSize()
  1542. text_width = max(width / (fontsize - 3), 70)
  1543. for id in self.label_id:
  1544. win = self.FindWindowById(id)
  1545. label = win.GetLabel()
  1546. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1547. win.SetLabel(label_new)
  1548. event.Skip()
  1549. class GrassGUIApp(wx.App):
  1550. """!Stand-alone GRASS command GUI
  1551. """
  1552. def __init__(self, grass_task):
  1553. self.grass_task = grass_task
  1554. wx.App.__init__(self, False)
  1555. def OnInit(self):
  1556. msg = self.grass_task.get_error_msg()
  1557. if msg:
  1558. gcmd.GError(msg + '\n\nTry to set up GRASS_ADDON_PATH variable.')
  1559. return True
  1560. self.mf = mainFrame(parent = None, ID = wx.ID_ANY, task_description = self.grass_task)
  1561. self.mf.CentreOnScreen()
  1562. self.mf.Show(True)
  1563. self.SetTopWindow(self.mf)
  1564. return True
  1565. class GUI:
  1566. def __init__(self, parent = None, show = True, modal = False,
  1567. centreOnParent = False, checkError = False):
  1568. """!Parses GRASS commands when module is imported and used from
  1569. Layer Manager.
  1570. """
  1571. self.parent = parent
  1572. self.show = show
  1573. self.modal = modal
  1574. self.centreOnParent = centreOnParent
  1575. self.checkError = checkError
  1576. self.grass_task = None
  1577. self.cmd = list()
  1578. global _blackList
  1579. if self.parent:
  1580. _blackList['enabled'] = True
  1581. else:
  1582. _blackList['enabled'] = False
  1583. def GetCmd(self):
  1584. """!Get validated command"""
  1585. return self.cmd
  1586. def ParseCommand(self, cmd, gmpath = None, completed = None):
  1587. """!Parse command
  1588. Note: cmd is given as list
  1589. If command is given with options, return validated cmd list:
  1590. - add key name for first parameter if not given
  1591. - change mapname to mapname@mapset
  1592. """
  1593. start = time.time()
  1594. dcmd_params = {}
  1595. if completed == None:
  1596. get_dcmd = None
  1597. layer = None
  1598. dcmd_params = None
  1599. else:
  1600. get_dcmd = completed[0]
  1601. layer = completed[1]
  1602. if completed[2]:
  1603. dcmd_params.update(completed[2])
  1604. # parse the interface decription
  1605. try:
  1606. global _blackList
  1607. self.grass_task = gtask.parse_interface(cmd[0],
  1608. blackList = _blackList)
  1609. except ValueError, e: #grass.ScriptError, e:
  1610. gcmd.GError(e.value)
  1611. return
  1612. # if layer parameters previously set, re-insert them into dialog
  1613. if completed is not None:
  1614. if 'params' in dcmd_params:
  1615. self.grass_task.params = dcmd_params['params']
  1616. if 'flags' in dcmd_params:
  1617. self.grass_task.flags = dcmd_params['flags']
  1618. err = list()
  1619. # update parameters if needed && validate command
  1620. if len(cmd) > 1:
  1621. i = 0
  1622. cmd_validated = [cmd[0]]
  1623. for option in cmd[1:]:
  1624. if option[0] == '-': # flag
  1625. if option[1] == '-':
  1626. self.grass_task.set_flag(option[2:], True)
  1627. else:
  1628. self.grass_task.set_flag(option[1], True)
  1629. cmd_validated.append(option)
  1630. else: # parameter
  1631. try:
  1632. key, value = option.split('=', 1)
  1633. except:
  1634. if i == 0: # add key name of first parameter if not given
  1635. key = self.grass_task.firstParam
  1636. value = option
  1637. else:
  1638. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  1639. element = self.grass_task.get_param(key, raiseError = False)
  1640. if not element:
  1641. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  1642. { 'cmd' : cmd[0],
  1643. 'key' : key })
  1644. continue
  1645. element = element['element']
  1646. if element in ['cell', 'vector']:
  1647. # mapname -> mapname@mapset
  1648. try:
  1649. name, mapset = value.split('@')
  1650. except ValueError:
  1651. mapset = grass.find_file(value, element)['mapset']
  1652. curr_mapset = grass.gisenv()['MAPSET']
  1653. if mapset and mapset != curr_mapset:
  1654. value = value + '@' + mapset
  1655. self.grass_task.set_param(key, value)
  1656. cmd_validated.append(key + '=' + value)
  1657. i += 1
  1658. # update original command list
  1659. cmd = cmd_validated
  1660. if self.show is not None:
  1661. self.mf = mainFrame(parent = self.parent, ID = wx.ID_ANY,
  1662. task_description = self.grass_task,
  1663. get_dcmd = get_dcmd, layer = layer)
  1664. else:
  1665. self.mf = None
  1666. if get_dcmd is not None:
  1667. # update only propwin reference
  1668. get_dcmd(dcmd = None, layer = layer, params = None,
  1669. propwin = self.mf)
  1670. if self.show is not None:
  1671. self.mf.notebookpanel.OnUpdateSelection(None)
  1672. if self.show is True:
  1673. if self.parent and self.centreOnParent:
  1674. self.mf.CentreOnParent()
  1675. else:
  1676. self.mf.CenterOnScreen()
  1677. self.mf.Show(self.show)
  1678. self.mf.MakeModal(self.modal)
  1679. else:
  1680. self.mf.OnApply(None)
  1681. self.cmd = cmd
  1682. if self.checkError:
  1683. return self.grass_task, err
  1684. else:
  1685. return self.grass_task
  1686. def GetCommandInputMapParamKey(self, cmd):
  1687. """!Get parameter key for input raster/vector map
  1688. @param cmd module name
  1689. @return parameter key
  1690. @return None on failure
  1691. """
  1692. # parse the interface decription
  1693. if not self.grass_task:
  1694. tree = etree.fromstring(gtask.get_interface_description(cmd))
  1695. self.grass_task = gtask.processTask(tree).get_task()
  1696. for p in self.grass_task.params:
  1697. if p.get('name', '') in ('input', 'map'):
  1698. age = p.get('age', '')
  1699. prompt = p.get('prompt', '')
  1700. element = p.get('element', '')
  1701. if age == 'old' and \
  1702. element in ('cell', 'grid3', 'vector') and \
  1703. prompt in ('raster', '3d-raster', 'vector'):
  1704. return p.get('name', None)
  1705. return None
  1706. class FloatValidator(wx.PyValidator):
  1707. """!Validator for floating-point input"""
  1708. def __init__(self):
  1709. wx.PyValidator.__init__(self)
  1710. self.Bind(wx.EVT_TEXT, self.OnText)
  1711. def Clone(self):
  1712. """!Clone validator"""
  1713. return FloatValidator()
  1714. def Validate(self):
  1715. """Validate input"""
  1716. textCtrl = self.GetWindow()
  1717. text = textCtrl.GetValue()
  1718. if text:
  1719. try:
  1720. float(text)
  1721. except ValueError:
  1722. textCtrl.SetBackgroundColour("grey")
  1723. textCtrl.SetFocus()
  1724. textCtrl.Refresh()
  1725. return False
  1726. sysColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)
  1727. textCtrl.SetBackgroundColour(sysColor)
  1728. textCtrl.Refresh()
  1729. return True
  1730. def OnText(self, event):
  1731. """!Do validation"""
  1732. self.Validate()
  1733. event.Skip()
  1734. def TransferToWindow(self):
  1735. return True # Prevent wxDialog from complaining.
  1736. def TransferFromWindow(self):
  1737. return True # Prevent wxDialog from complaining.
  1738. class GNotebook(FN.FlatNotebook):
  1739. """!Generic notebook widget
  1740. """
  1741. def __init__(self, parent, style, **kwargs):
  1742. if globalvar.hasAgw:
  1743. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, agwStyle = style, **kwargs)
  1744. else:
  1745. FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, style = style, **kwargs)
  1746. self.notebookPages = {}
  1747. def AddPage(self, **kwargs):
  1748. """!Add a new page
  1749. """
  1750. if 'name' in kwargs:
  1751. self.notebookPages[kwargs['name']] = kwargs['page']
  1752. del kwargs['name']
  1753. super(GNotebook, self).AddPage(**kwargs)
  1754. def InsertPage(self, **kwargs):
  1755. """!Insert a new page
  1756. """
  1757. if 'name' in kwargs:
  1758. self.notebookPages[kwargs['name']] = kwargs['page']
  1759. del kwargs['name']
  1760. super(GNotebook, self).InsertPage(**kwargs)
  1761. def SetSelectionByName(self, page):
  1762. """!Set notebook
  1763. @param page names, eg. 'layers', 'output', 'search', 'pyshell', 'nviz'
  1764. """
  1765. if self.GetSelection() != self.GetPageIndexByName('output'):
  1766. self.SetSelection(self.GetPageIndexByName(page))
  1767. def GetPageIndexByName(self, page):
  1768. """!Get notebook page index
  1769. @param page name
  1770. """
  1771. if page not in self.notebookPages:
  1772. return -1
  1773. return self.GetPageIndex(self.notebookPages[page])
  1774. if __name__ == "__main__":
  1775. import gettext
  1776. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1777. if len(sys.argv) == 1:
  1778. sys.exit(_("usage: %s <grass command>") % sys.argv[0])
  1779. if sys.argv[1] != 'test':
  1780. q = wx.LogNull()
  1781. cmd = utils.split(sys.argv[1])
  1782. task = gtask.grassTask(cmd[0], blackList = _blackList)
  1783. task.set_options(cmd[1:])
  1784. app = GrassGUIApp(task)
  1785. app.MainLoop()
  1786. else: #Test
  1787. # Test grassTask from within a GRASS session
  1788. if os.getenv("GISBASE") is not None:
  1789. task = gtask.grassTask("d.vect")
  1790. task.get_param('map')['value'] = "map_name"
  1791. task.get_flag('v')['value'] = True
  1792. task.get_param('layer')['value'] = 1
  1793. task.get_param('bcolor')['value'] = "red"
  1794. assert ' '.join(task.getCmd()) == "d.vect -v map = map_name layer = 1 bcolor = red"
  1795. # Test interface building with handmade grassTask,
  1796. # possibly outside of a GRASS session.
  1797. task = gtask.grassTask()
  1798. task.name = "TestTask"
  1799. task.description = "This is an artificial grassTask() object intended for testing purposes."
  1800. task.keywords = ["grass","test","task"]
  1801. task.params = [
  1802. {
  1803. "name" : "text",
  1804. "description" : "Descriptions go into tooltips if labels are present, like this one",
  1805. "label" : "Enter some text",
  1806. },{
  1807. "name" : "hidden_text",
  1808. "description" : "This text should not appear in the form",
  1809. "hidden" : True
  1810. },{
  1811. "name" : "text_default",
  1812. "description" : "Enter text to override the default",
  1813. "default" : "default text"
  1814. },{
  1815. "name" : "text_prefilled",
  1816. "description" : "You should see a friendly welcome message here",
  1817. "value" : "hello, world"
  1818. },{
  1819. "name" : "plain_color",
  1820. "description" : "This is a plain color, and it is a compulsory parameter",
  1821. "required" : False,
  1822. "gisprompt" : True,
  1823. "prompt" : "color"
  1824. },{
  1825. "name" : "transparent_color",
  1826. "description" : "This color becomes transparent when set to none",
  1827. "guisection" : "tab",
  1828. "gisprompt" : True,
  1829. "prompt" : "color"
  1830. },{
  1831. "name" : "multi",
  1832. "description" : "A multiple selection",
  1833. 'default': u'red,green,blue',
  1834. 'gisprompt': False,
  1835. 'guisection': 'tab',
  1836. 'multiple': u'yes',
  1837. 'type': u'string',
  1838. 'value': '',
  1839. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other']
  1840. },{
  1841. "name" : "single",
  1842. "description" : "A single multiple-choice selection",
  1843. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  1844. "guisection" : "tab"
  1845. },{
  1846. "name" : "large_multi",
  1847. "description" : "A large multiple selection",
  1848. "gisprompt" : False,
  1849. "multiple" : "yes",
  1850. # values must be an array of strings
  1851. "values" : str2rgb.keys() + map(str, str2rgb.values())
  1852. },{
  1853. "name" : "a_file",
  1854. "description" : "A file selector",
  1855. "gisprompt" : True,
  1856. "element" : "file"
  1857. }
  1858. ]
  1859. task.flags = [
  1860. {
  1861. "name" : "a",
  1862. "description" : "Some flag, will appear in Main since it is required",
  1863. "required" : True
  1864. },{
  1865. "name" : "b",
  1866. "description" : "pre-filled flag, will appear in options since it is not required",
  1867. "value" : True
  1868. },{
  1869. "name" : "hidden_flag",
  1870. "description" : "hidden flag, should not be changeable",
  1871. "hidden" : "yes",
  1872. "value" : True
  1873. }
  1874. ]
  1875. q = wx.LogNull()
  1876. GrassGUIApp(task).MainLoop()