forms.py 93 KB

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