forms.py 86 KB

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