forms.py 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640
  1. """
  2. @package gui_core.forms
  3. @brief Construct simple wxPython GUI from a GRASS command interface
  4. description.
  5. Classes:
  6. - forms::UpdateThread
  7. - forms::UpdateQThread
  8. - forms::TaskFrame
  9. - forms::CmdPanel
  10. - forms::GUI
  11. - forms::GrassGUIApp
  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-2015 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. @author Stepan Turek <stepan.turek seznam.cz> (CoordinatesSelect)
  35. """
  36. import sys
  37. import string
  38. import textwrap
  39. import os
  40. import copy
  41. import locale
  42. import Queue
  43. import re
  44. import codecs
  45. from threading import Thread
  46. if not os.getenv("GISBASE"):
  47. sys.write("We don't seem to be properly installed, or we are being run "
  48. "outside GRASS. Expect glitches.\n")
  49. gisbase = os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir)
  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. from wx.lib.newevent import NewEvent
  58. try:
  59. import xml.etree.ElementTree as etree
  60. except ImportError:
  61. import elementtree.ElementTree as etree # Python <= 2.4
  62. from grass.pydispatch.signal import Signal
  63. from grass.script import core as grass
  64. from grass.script import task as gtask
  65. from core import globalvar
  66. from gui_core.widgets import StaticWrapText, ScrolledPanel, ColorTablesComboBox, \
  67. BarscalesComboBox, NArrowsComboBox
  68. from gui_core.ghelp import HelpPanel
  69. from gui_core import gselect
  70. from core import gcmd
  71. from core import utils
  72. from core.utils import _
  73. from core.settings import UserSettings
  74. from gui_core.widgets import FloatValidator, GNotebook, FormNotebook, FormListbook
  75. from core.giface import Notification
  76. wxUpdateDialog, EVT_DIALOG_UPDATE = NewEvent()
  77. """Hide some options in the GUI"""
  78. #_blackList = { 'enabled' : False,
  79. # 'items' : { 'r.buffer' : {'params' : ['input', 'output'],
  80. # 'flags' : ['z', 'overwrite']}}}
  81. _blackList = { 'enabled' : False,
  82. 'items' : {} }
  83. def text_beautify(someString , width = 70):
  84. """Make really long texts shorter, clean up whitespace and remove
  85. trailing punctuation.
  86. """
  87. if width > 0:
  88. return escape_ampersand(string.strip(
  89. os.linesep.join(textwrap.wrap(utils.normalize_whitespace(someString), width)),
  90. ".,;:"))
  91. else:
  92. return escape_ampersand(string.strip(utils.normalize_whitespace(someString), ".,;:"))
  93. def escape_ampersand(text):
  94. """Escapes ampersands with additional ampersand for GUI"""
  95. return string.replace(text, "&", "&&")
  96. class UpdateThread(Thread):
  97. """Update dialog widgets in the thread"""
  98. def __init__(self, parent, event, eventId, task):
  99. Thread.__init__(self)
  100. self.parent = parent
  101. self.event = event
  102. self.eventId = eventId
  103. self.task = task
  104. self.setDaemon(True)
  105. # list of functions which updates the dialog
  106. self.data = {}
  107. def run(self):
  108. # get widget id
  109. if not self.eventId:
  110. for p in self.task.params:
  111. if p.get('gisprompt', False) == False:
  112. continue
  113. prompt = p.get('element', '')
  114. if prompt == 'vector':
  115. name = p.get('name', '')
  116. if name in ('map', 'input'):
  117. self.eventId = p['wxId'][0]
  118. if self.eventId is None:
  119. return
  120. p = self.task.get_param(self.eventId, element = 'wxId', raiseError = False)
  121. if not p or 'wxId-bind' not in p:
  122. return
  123. # is this check necessary?
  124. # get widget prompt
  125. # pType = p.get('prompt', '')
  126. # if not pType:
  127. # return
  128. # check for map/input parameter
  129. pMap = self.task.get_param('map', raiseError = False)
  130. if not pMap:
  131. pMap = self.task.get_param('input', raiseError = False)
  132. if pMap:
  133. map = pMap.get('value', '')
  134. else:
  135. map = None
  136. # avoid running db.describe several times
  137. cparams = dict()
  138. cparams[map] = { 'dbInfo' : None,
  139. 'layers' : None, }
  140. # update reference widgets
  141. for uid in p['wxId-bind']:
  142. win = self.parent.FindWindowById(uid)
  143. if not win:
  144. continue
  145. name = win.GetName()
  146. ### @todo: replace name by isinstance() and signals
  147. pBind = self.task.get_param(uid, element = 'wxId', raiseError = False)
  148. if pBind:
  149. pBind['value'] = ''
  150. # set appropriate types in t.* modules and g.list/remove element selections
  151. if name == 'Select':
  152. type_param = self.task.get_param('type', element='name', raiseError=False)
  153. if 'all' in type_param.get('value'):
  154. etype = type_param.get('values')[:]
  155. if 'all' in etype:
  156. etype.remove('all')
  157. etype = ','.join(etype)
  158. else:
  159. etype = type_param.get('value')
  160. if globalvar.CheckWxVersion([3]):
  161. self.data[win.SetElementList] = {'type': etype}
  162. else:
  163. self.data[win.GetParent().SetElementList] = {'type': etype}
  164. # t.(un)register has one type for 'input', 'maps'
  165. maps_param = self.task.get_param('maps', element='name', raiseError=False)
  166. if self.task.get_name().startswith('t') and maps_param is not None:
  167. if maps_param['wxId'][0] != uid:
  168. element_dict = {'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
  169. self.data[win.GetParent().SetType] = {'etype': element_dict[type_param.get('value')]}
  170. map = layer = None
  171. driver = db = None
  172. if name in ('LayerSelect', 'ColumnSelect'):
  173. if p.get('element', '') == 'vector': # -> vector
  174. # get map name
  175. map = p.get('value', '')
  176. # get layer
  177. for bid in p['wxId-bind']:
  178. p = self.task.get_param(bid, element = 'wxId', raiseError = False)
  179. if not p:
  180. continue
  181. if p.get('element', '') in ['layer', 'layer_all']:
  182. layer = p.get('value', '')
  183. if layer != '':
  184. layer = p.get('value', '')
  185. else:
  186. layer = p.get('default', '')
  187. break
  188. elif p.get('element', '') in ['layer', 'layer_all']: # -> layer
  189. # get layer
  190. layer = p.get('value', '')
  191. if layer != '':
  192. layer = p.get('value', '')
  193. else:
  194. layer = p.get('default', '')
  195. # get map name
  196. pMapL = self.task.get_param(p['wxId'][0], element = 'wxId-bind', raiseError = False)
  197. if pMapL:
  198. map = pMapL.get('value', '')
  199. if name == 'TableSelect' or \
  200. (name == 'ColumnSelect' and not map):
  201. pDriver = self.task.get_param('dbdriver', element = 'prompt', raiseError = False)
  202. if pDriver:
  203. driver = pDriver.get('value', '')
  204. pDb = self.task.get_param('dbname', element = 'prompt', raiseError = False)
  205. if pDb:
  206. db = pDb.get('value', '')
  207. if name == 'ColumnSelect':
  208. pTable = self.task.get_param('dbtable', element = 'element', raiseError = False)
  209. if pTable:
  210. table = pTable.get('value', '')
  211. if name == 'LayerSelect':
  212. # determine format
  213. native = True
  214. for id in pMap['wxId']:
  215. winVec = self.parent.FindWindowById(id)
  216. if winVec.GetName() == 'VectorFormat' and \
  217. winVec.GetSelection() != 0:
  218. native = False
  219. break
  220. # TODO: update only if needed
  221. if native:
  222. if map:
  223. self.data[win.InsertLayers] = { 'vector' : map }
  224. else:
  225. self.data[win.InsertLayers] = { }
  226. else:
  227. if map:
  228. self.data[win.InsertLayers] = { 'dsn' : map.rstrip('@OGR') }
  229. else:
  230. self.data[win.InsertLayers] = { }
  231. elif name == 'TableSelect':
  232. self.data[win.InsertTables] = { 'driver' : driver,
  233. 'database' : db }
  234. elif name == 'ColumnSelect':
  235. if map:
  236. if map in cparams:
  237. if not cparams[map]['dbInfo']:
  238. cparams[map]['dbInfo'] = gselect.VectorDBInfo(map)
  239. self.data[win.GetParent().InsertColumns] = { 'vector' : map, 'layer' : layer,
  240. 'dbInfo' : cparams[map]['dbInfo'] }
  241. else: # table
  242. if driver and db:
  243. self.data[win.GetParent().InsertTableColumns] = { 'table' : pTable.get('value'),
  244. 'driver' : driver,
  245. 'database' : db }
  246. elif pTable:
  247. self.data[win.GetParent().InsertTableColumns] = { 'table' : pTable.get('value') }
  248. elif name == 'SubGroupSelect':
  249. self.data[win.Insert] = { 'group' : p.get('value', '')}
  250. elif name == 'SignatureSelect':
  251. if p.get('prompt', 'group') == 'group':
  252. group = p.get('value', '')
  253. pSubGroup = self.task.get_param('subgroup', element = 'prompt', raiseError = False)
  254. if pSubGroup:
  255. subgroup = pSubGroup.get('value', '')
  256. else:
  257. subgroup = None
  258. else:
  259. subgroup = p.get('value', '')
  260. pGroup = self.task.get_param('group', element = 'prompt', raiseError = False)
  261. if pGroup:
  262. group = pGroup.get('value', '')
  263. else:
  264. group = None
  265. self.data[win.Insert] = { 'group' : group,
  266. 'subgroup' : subgroup}
  267. elif name == 'LocationSelect':
  268. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  269. if pDbase:
  270. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', '')}
  271. elif name == 'MapsetSelect':
  272. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  273. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  274. if pDbase and pLocation:
  275. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  276. 'location' : pLocation.get('value', '')}
  277. elif name == 'ProjSelect':
  278. pDbase = self.task.get_param('dbase', element = 'element', raiseError = False)
  279. pLocation = self.task.get_param('location', element = 'element', raiseError = False)
  280. pMapset = self.task.get_param('mapset', element = 'element', raiseError = False)
  281. if pDbase and pLocation and pMapset:
  282. self.data[win.UpdateItems] = { 'dbase' : pDbase.get('value', ''),
  283. 'location' : pLocation.get('value', ''),
  284. 'mapset' : pMapset.get('value', '')}
  285. def UpdateDialog(parent, event, eventId, task):
  286. return UpdateThread(parent, event, eventId, task)
  287. class UpdateQThread(Thread):
  288. """Update dialog widgets in the thread"""
  289. requestId = 0
  290. def __init__(self, parent, requestQ, resultQ, **kwds):
  291. Thread.__init__(self, **kwds)
  292. self.parent = parent # cmdPanel
  293. self.setDaemon(True)
  294. self.requestQ = requestQ
  295. self.resultQ = resultQ
  296. self.start()
  297. def Update(self, callable, *args, **kwds):
  298. UpdateQThread.requestId += 1
  299. self.request = None
  300. self.requestQ.put((UpdateQThread.requestId, callable, args, kwds))
  301. return UpdateQThread.requestId
  302. def run(self):
  303. while True:
  304. requestId, callable, args, kwds = self.requestQ.get()
  305. self.request = callable(*args, **kwds)
  306. self.resultQ.put((requestId, self.request.run()))
  307. if self.request:
  308. event = wxUpdateDialog(data = self.request.data)
  309. wx.PostEvent(self.parent, event)
  310. class TaskFrame(wx.Frame):
  311. """This is the Frame containing the dialog for options input.
  312. The dialog is organized in a notebook according to the guisections
  313. defined by each GRASS command.
  314. If run with a parent, it may Apply, Ok or Cancel; the latter two
  315. close the dialog. The former two trigger a callback.
  316. If run standalone, it will allow execution of the command.
  317. The command is checked and sent to the clipboard when clicking
  318. 'Copy'.
  319. """
  320. def __init__(self, parent, giface, task_description, id = wx.ID_ANY,
  321. get_dcmd = None, layer = None,
  322. style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL, **kwargs):
  323. self.get_dcmd = get_dcmd
  324. self.layer = layer
  325. self.task = task_description
  326. self.parent = parent # LayerTree | Modeler | None | ...
  327. self._giface = giface
  328. self.dialogClosing = Signal('TaskFrame.dialogClosing')
  329. # module name + keywords
  330. title = self.task.get_name()
  331. try:
  332. if self.task.keywords != ['']:
  333. title += " [" + ', '.join(self.task.keywords) + "]"
  334. except ValueError:
  335. pass
  336. wx.Frame.__init__(self, parent = parent, id = id, title = title,
  337. name = "MainFrame", style = style, **kwargs)
  338. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  339. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  340. # statusbar
  341. self.CreateStatusBar()
  342. # icon
  343. self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_dialog.ico'), wx.BITMAP_TYPE_ICO))
  344. guisizer = wx.BoxSizer(wx.VERTICAL)
  345. # set apropriate output window
  346. if self.parent:
  347. self.standalone = False
  348. else:
  349. self.standalone = True
  350. # logo + description
  351. topsizer = wx.BoxSizer(wx.HORIZONTAL)
  352. # GRASS logo
  353. self.logo = wx.StaticBitmap(parent = self.panel,
  354. bitmap = wx.Bitmap(name = os.path.join(globalvar.IMGDIR,
  355. 'grass_form.png'),
  356. type = wx.BITMAP_TYPE_PNG))
  357. topsizer.Add(item = self.logo, proportion = 0, border = 3,
  358. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL)
  359. # add module description
  360. if self.task.label:
  361. module_desc = self.task.label + ' ' + self.task.description
  362. else:
  363. module_desc = self.task.description
  364. self.description = StaticWrapText(parent=self.panel,
  365. label=module_desc)
  366. topsizer.Add(item = self.description, proportion = 1, border = 5,
  367. flag = wx.ALL | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
  368. guisizer.Add(item = topsizer, proportion = 0, flag = wx.EXPAND)
  369. self.panel.SetSizerAndFit(guisizer)
  370. self.Layout()
  371. # notebooks
  372. self.notebookpanel = CmdPanel(parent = self.panel, giface = self._giface, task = self.task,
  373. frame = self)
  374. self._gconsole = self.notebookpanel._gconsole
  375. if self._gconsole:
  376. self._gconsole.mapCreated.connect(self.OnMapCreated)
  377. self._gconsole.updateMap.connect(lambda: self._giface.updateMap.emit())
  378. self.goutput = self.notebookpanel.goutput
  379. if self.goutput:
  380. self.goutput.showNotification.connect(lambda message: self.SetStatusText(message))
  381. self.notebookpanel.OnUpdateValues = self.updateValuesHook
  382. guisizer.Add(item = self.notebookpanel, proportion = 1, flag = wx.EXPAND)
  383. # status bar
  384. status_text = _("Enter parameters for '") + self.task.name + "'"
  385. try:
  386. self.task.get_cmd()
  387. self.updateValuesHook()
  388. except ValueError:
  389. self.SetStatusText(status_text)
  390. # buttons
  391. btnsizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  392. # cancel
  393. self.btn_cancel = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  394. self.btn_cancel.SetToolTipString(_("Close this window without executing the command (Ctrl+Q)"))
  395. btnsizer.Add(item = self.btn_cancel, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  396. self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
  397. # bind closing to ESC and CTRL+Q
  398. self.Bind(wx.EVT_MENU, self.OnCancel, id=wx.ID_CLOSE)
  399. accelTableList = [(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_CLOSE)]
  400. accelTableList = [(wx.ACCEL_CTRL, ord('Q'), wx.ID_CLOSE)]
  401. # TODO: bind Ctrl-t for tile windows here (trac #2004)
  402. if self.get_dcmd is not None: # A callback has been set up
  403. btn_apply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
  404. btn_ok = wx.Button(parent = self.panel, id = wx.ID_OK)
  405. btn_ok.SetDefault()
  406. btnsizer.Add(item = btn_apply, proportion = 0,
  407. flag = wx.ALL | wx.ALIGN_CENTER,
  408. border = 10)
  409. btnsizer.Add(item = btn_ok, proportion = 0,
  410. flag = wx.ALL | wx.ALIGN_CENTER,
  411. border = 10)
  412. btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
  413. btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
  414. else: # We're standalone
  415. # run
  416. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_OK, label = _("&Run"))
  417. self.btn_run.SetToolTipString(_("Run the command (Ctrl+R)"))
  418. self.btn_run.SetDefault()
  419. self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
  420. btnsizer.Add(item = self.btn_run, proportion = 0,
  421. flag = wx.ALL | wx.ALIGN_CENTER,
  422. border = 10)
  423. self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)
  424. self.Bind(wx.EVT_MENU, self.OnRun, id=wx.ID_OK)
  425. accelTableList.append((wx.ACCEL_CTRL, ord('R'), wx.ID_OK))
  426. # copy
  427. self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
  428. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard"))
  429. btnsizer.Add(item=self.btn_clipboard, proportion=0,
  430. flag=wx.ALL | wx.ALIGN_CENTER,
  431. border=10)
  432. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  433. # help
  434. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  435. self.btn_help.SetToolTipString(_("Show manual page of the command (Ctrl+H)"))
  436. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  437. self.Bind(wx.EVT_MENU, self.OnHelp, id=wx.ID_HELP)
  438. accelTableList.append((wx.ACCEL_CTRL, ord('H'), wx.ID_HELP))
  439. if self.notebookpanel.notebook.GetPageIndexByName('manual') < 0:
  440. self.btn_help.Hide()
  441. # add help button
  442. btnsizer.Add(item = self.btn_help, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 10)
  443. guisizer.Add(item = btnsizer, proportion = 0, flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT,
  444. border = 30)
  445. # abort key bindings
  446. abortId = wx.NewId()
  447. self.Bind(wx.EVT_MENU, self.OnAbort, id=abortId)
  448. accelTableList.append((wx.ACCEL_CTRL, ord('S'), abortId))
  449. # set accelerator table
  450. accelTable = wx.AcceleratorTable(accelTableList)
  451. self.SetAcceleratorTable(accelTable)
  452. if self._giface and self._giface.GetLayerTree():
  453. addLayer = False
  454. for p in self.task.params:
  455. if p.get('age', 'old') == 'new' and \
  456. p.get('prompt', '') in ('raster', 'vector', '3d-raster'):
  457. addLayer = True
  458. if addLayer:
  459. # add newly created map into layer tree
  460. self.addbox = wx.CheckBox(parent = self.panel,
  461. label = _('Add created map(s) into layer tree'), style = wx.NO_BORDER)
  462. self.addbox.SetValue(UserSettings.Get(group = 'cmd', key = 'addNewLayer', subkey = 'enabled'))
  463. guisizer.Add(item = self.addbox, proportion = 0,
  464. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  465. border = 5)
  466. hasNew = False
  467. for p in self.task.params:
  468. if p.get('age', 'old') == 'new':
  469. hasNew = True
  470. break
  471. if self.get_dcmd is None and hasNew:
  472. # close dialog when command is terminated
  473. self.closebox = wx.CheckBox(parent = self.panel,
  474. label = _('Close dialog on finish'), style = wx.NO_BORDER)
  475. self.closebox.SetValue(UserSettings.Get(group = 'cmd', key = 'closeDlg', subkey = 'enabled'))
  476. self.closebox.SetToolTipString(_("Close dialog when command is successfully finished. "
  477. "Change this settings in Preferences dialog ('Command' tab)."))
  478. guisizer.Add(item = self.closebox, proportion = 0,
  479. flag = wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
  480. border = 5)
  481. # bindings
  482. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  483. # do layout
  484. # called automatically by SetSizer()
  485. self.panel.SetAutoLayout(True)
  486. self.panel.SetSizerAndFit(guisizer)
  487. sizeFrame = self.GetBestSize()
  488. self.SetMinSize(sizeFrame)
  489. if hasattr(self, "closebox"):
  490. scale = 0.33
  491. else:
  492. scale = 0.50
  493. self.SetSize(wx.Size(sizeFrame[0], sizeFrame[1] + scale * max(self.notebookpanel.panelMinHeight,
  494. self.notebookpanel.constrained_size[1])))
  495. # thread to update dialog
  496. # create queues
  497. self.requestQ = Queue.Queue()
  498. self.resultQ = Queue.Queue()
  499. self.updateThread = UpdateQThread(self.notebookpanel, self.requestQ, self.resultQ)
  500. self.Layout()
  501. # keep initial window size limited for small screens
  502. width, height = self.GetSizeTuple()
  503. self.SetSize(wx.Size(min(width, 650),
  504. min(height, 500)))
  505. # fix goutput's pane size (required for Mac OSX)
  506. if self.goutput:
  507. self.goutput.SetSashPosition(int(self.GetSize()[1] * .75))
  508. def updateValuesHook(self, event = None):
  509. """Update status bar data"""
  510. self.SetStatusText(' '.join([gcmd.DecodeString(each) if isinstance(each, str) else each
  511. for each in self.notebookpanel.createCmd(ignoreErrors=True)]))
  512. if event:
  513. event.Skip()
  514. def OnDone(self, event):
  515. """This function is launched from OnRun() when command is
  516. finished
  517. """
  518. if hasattr(self, "btn_cancel"):
  519. self.btn_cancel.Enable(True)
  520. if hasattr(self, "btn_clipboard"):
  521. self.btn_clipboard.Enable(True)
  522. if hasattr(self, "btn_help"):
  523. self.btn_help.Enable(True)
  524. if hasattr(self, "btn_run"):
  525. self.btn_run.Enable(True)
  526. if hasattr(self, "get_dcmd") and \
  527. self.get_dcmd is None and \
  528. hasattr(self, "closebox") and \
  529. self.closebox.IsChecked() and \
  530. (event.returncode == 0):
  531. # was closed also when aborted but better is leave it open
  532. wx.FutureCall(2000, self.Close)
  533. def OnMapCreated(self, name, ltype):
  534. """Map created or changed
  535. :param name: map name
  536. :param ltype: layer type (prompt value)
  537. """
  538. if hasattr(self, "addbox") and self.addbox.IsChecked():
  539. add = True
  540. else:
  541. add = False
  542. if self._giface:
  543. self._giface.mapCreated.emit(name=name, ltype=ltype, add=add)
  544. def OnOK(self, event):
  545. """OK button pressed"""
  546. cmd = self.OnApply(event)
  547. if cmd is not None and self.get_dcmd is not None:
  548. self.OnCancel(event)
  549. def OnApply(self, event):
  550. """Apply the command"""
  551. if self._giface and hasattr(self._giface, "_model"):
  552. cmd = self.createCmd(ignoreErrors = True, ignoreRequired = True)
  553. else:
  554. cmd = self.createCmd()
  555. if cmd is not None and self.get_dcmd is not None:
  556. # return d.* command to layer tree for rendering
  557. self.get_dcmd(cmd, self.layer, {"params": self.task.params,
  558. "flags" : self.task.flags},
  559. self)
  560. # echo d.* command to output console
  561. # self.parent.writeDCommand(cmd)
  562. return cmd
  563. def OnRun(self, event):
  564. """Run the command"""
  565. cmd = self.createCmd()
  566. if not cmd or len(cmd) < 1:
  567. return
  568. ret = 0
  569. if self.standalone or cmd[0][0:2] != "d.":
  570. # Send any non-display command to parent window (probably wxgui.py)
  571. # put to parents switch to 'Command output'
  572. self.notebookpanel.notebook.SetSelectionByName('output')
  573. try:
  574. if self.task.path:
  575. cmd[0] = self.task.path # full path
  576. ret = self._gconsole.RunCmd(cmd, onDone = self.OnDone)
  577. except AttributeError as e:
  578. print >> sys.stderr, "%s: Probably not running in wxgui.py session?" % (e)
  579. print >> sys.stderr, "parent window is: %s" % (str(self.parent))
  580. else:
  581. gcmd.Command(cmd)
  582. if ret != 0:
  583. self.notebookpanel.notebook.SetSelection(0)
  584. return
  585. # update buttons status
  586. for btn in (self.btn_run,
  587. self.btn_cancel,
  588. self.btn_clipboard,
  589. self.btn_help):
  590. btn.Enable(False)
  591. def OnAbort(self, event):
  592. """Abort running command"""
  593. from core.gconsole import wxCmdAbort
  594. event = wxCmdAbort(aborted = True)
  595. wx.PostEvent(self._gconsole, event)
  596. def OnCopy(self, event):
  597. """Copy the command"""
  598. cmddata = wx.TextDataObject()
  599. # list -> string
  600. cmdlist = self.createCmd(ignoreErrors = True)
  601. # TODO: better protect whitespace with quotes
  602. for i in range(1, len(cmdlist)):
  603. if ' ' in cmdlist[i]:
  604. optname, val = cmdlist[i].split("=", 1)
  605. cmdlist[i] = '%s="%s"' % (optname, val)
  606. cmdstring = ' '.join(cmdlist)
  607. cmddata.SetText(cmdstring)
  608. if wx.TheClipboard.Open():
  609. # wx.TheClipboard.UsePrimarySelection(True)
  610. wx.TheClipboard.SetData(cmddata)
  611. wx.TheClipboard.Close()
  612. self.SetStatusText(_("'%s' copied to clipboard") % \
  613. (cmdstring))
  614. def OnCancel(self, event):
  615. """Cancel button pressed"""
  616. self.MakeModal(False)
  617. self.dialogClosing.emit()
  618. if self.get_dcmd and \
  619. self.parent and \
  620. self.parent.GetName() in ('LayerTree',
  621. 'MapWindow'):
  622. # display decorations and
  623. # pressing OK or cancel after setting layer properties
  624. if self.task.name in ['d.barscale','d.legend', 'd.northarrow', 'd.histogram'] \
  625. or len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) >= 1:
  626. self.Hide()
  627. # canceled layer with nothing set
  628. elif len(self.parent.GetLayerInfo(self.layer, key = 'cmd')) < 1:
  629. try:
  630. self.parent.Delete(self.layer)
  631. except ValueError:
  632. # happens when closing dialog of a new layer which was removed from tree
  633. pass
  634. self.Destroy()
  635. else:
  636. # cancel for non-display commands
  637. self.Destroy()
  638. def OnHelp(self, event):
  639. """Show manual page (switch to the 'Manual' notebook page)"""
  640. if self.notebookpanel.notebook.GetPageIndexByName('manual') > -1:
  641. self.notebookpanel.notebook.SetSelectionByName('manual')
  642. self.notebookpanel.OnPageChange(None)
  643. if event:
  644. event.Skip()
  645. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  646. """Create command string (python list)"""
  647. return self.notebookpanel.createCmd(ignoreErrors = ignoreErrors,
  648. ignoreRequired = ignoreRequired)
  649. class CmdPanel(wx.Panel):
  650. """A panel containing a notebook dividing in tabs the different
  651. guisections of the GRASS cmd.
  652. """
  653. def __init__(self, parent, giface, task, id = wx.ID_ANY, frame = None, *args, **kwargs):
  654. if frame:
  655. self.parent = frame
  656. else:
  657. self.parent = parent
  658. self.task = task
  659. self._giface = giface
  660. wx.Panel.__init__(self, parent, id = id, *args, **kwargs)
  661. self.mapCreated = Signal
  662. self.updateMap = Signal
  663. # Determine tab layout
  664. sections = []
  665. is_section = {}
  666. not_hidden = [ p for p in self.task.params + self.task.flags if not p.get('hidden', False) == True ]
  667. self.label_id = [] # wrap titles on resize
  668. self.Bind(wx.EVT_SIZE, self.OnSize)
  669. for task in not_hidden:
  670. if task.get('required', False) and not task.get('guisection', ''):
  671. # All required go into Main, even if they had defined another guisection
  672. task['guisection'] = _('Required')
  673. if task.get('guisection','') == '':
  674. # Undefined guisections end up into Options
  675. task['guisection'] = _('Optional')
  676. if task['guisection'] not in is_section:
  677. # We do it like this to keep the original order, except for Main which goes first
  678. is_section[task['guisection']] = 1
  679. sections.append(task['guisection'])
  680. else:
  681. is_section[ task['guisection'] ] += 1
  682. del is_section
  683. # 'Required' tab goes first, 'Optional' as the last one
  684. for (newidx,content) in [ (0,_('Required')), (len(sections)-1,_('Optional')) ]:
  685. if content in sections:
  686. idx = sections.index(content)
  687. sections[idx:idx+1] = []
  688. sections[newidx:newidx] = [content]
  689. panelsizer = wx.BoxSizer(orient = wx.VERTICAL)
  690. # build notebook
  691. style = UserSettings.Get(group = 'appearance', key = 'commandNotebook', subkey = 'selection')
  692. if style == 0: # basic top
  693. self.notebook = FormNotebook(self, style = wx.BK_TOP)
  694. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  695. elif style == 1: # basic left
  696. self.notebook = FormNotebook(self, style = wx.BK_LEFT)
  697. self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  698. elif style == 2: # fancy green
  699. self.notebook = GNotebook(self, style = globalvar.FNPageStyle | FN.FNB_NO_X_BUTTON )
  700. self.notebook.SetTabAreaColour(globalvar.FNPageColor)
  701. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChange)
  702. elif style == 3:
  703. self.notebook = FormListbook(self, style = wx.BK_LEFT)
  704. self.notebook.Bind(wx.EVT_LISTBOOK_PAGE_CHANGED, self.OnPageChange)
  705. self.notebook.Refresh()
  706. tab = {}
  707. tabsizer = {}
  708. for section in sections:
  709. tab[section] = ScrolledPanel(parent = self.notebook)
  710. tab[section].SetScrollRate(10, 10)
  711. tabsizer[section] = wx.BoxSizer(orient = wx.VERTICAL)
  712. #
  713. # flags
  714. #
  715. visible_flags = [ f for f in self.task.flags if not f.get('hidden', False) == True ]
  716. for f in visible_flags:
  717. # we don't want another help (checkbox appeared in r58783)
  718. if f['name'] == 'help':
  719. continue
  720. which_sizer = tabsizer[ f['guisection'] ]
  721. which_panel = tab[ f['guisection'] ]
  722. # if label is given: description -> tooltip
  723. if f.get('label','') != '':
  724. title = text_beautify(f['label'])
  725. tooltip = text_beautify(f['description'], width = -1)
  726. else:
  727. title = text_beautify(f['description'])
  728. tooltip = None
  729. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  730. rtitle_txt = wx.StaticText(parent = which_panel,
  731. label = '(' + f['name'] + ')')
  732. chk = wx.CheckBox(parent = which_panel, label = title, style = wx.NO_BORDER)
  733. self.label_id.append(chk.GetId())
  734. if tooltip:
  735. chk.SetToolTipString(tooltip)
  736. chk.SetValue(f.get('value', False))
  737. title_sizer.Add(item = chk, proportion = 1,
  738. flag = wx.EXPAND)
  739. title_sizer.Add(item = rtitle_txt, proportion = 0,
  740. flag = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)
  741. which_sizer.Add(item = title_sizer, proportion = 0,
  742. flag = wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border = 5)
  743. f['wxId'] = [ chk.GetId(), ]
  744. chk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  745. if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
  746. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  747. label = _("Parameterized in model"))
  748. parChk.SetName('ModelParam')
  749. parChk.SetValue(f.get('parameterized', False))
  750. if 'wxId' in f:
  751. f['wxId'].append(parChk.GetId())
  752. else:
  753. f['wxId'] = [ parChk.GetId() ]
  754. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  755. which_sizer.Add(item = parChk, proportion = 0,
  756. flag = wx.LEFT, border = 20)
  757. if f['name'] in ('verbose', 'quiet'):
  758. chk.Bind(wx.EVT_CHECKBOX, self.OnVerbosity)
  759. vq = UserSettings.Get(group = 'cmd', key = 'verbosity', subkey = 'selection')
  760. if f['name'] == vq:
  761. chk.SetValue(True)
  762. f['value'] = True
  763. if f['name'] == 'overwrite':
  764. value = UserSettings.Get(group = 'cmd', key = 'overwrite', subkey = 'enabled')
  765. if value: # override only when enabled
  766. f['value'] = value
  767. chk.SetValue(f['value'])
  768. #
  769. # parameters
  770. #
  771. visible_params = [ p for p in self.task.params if not p.get('hidden', False) == True ]
  772. try:
  773. first_param = visible_params[0]
  774. except IndexError:
  775. first_param = None
  776. for p in visible_params:
  777. which_sizer = tabsizer[p['guisection']]
  778. which_panel = tab[p['guisection']]
  779. # if label is given -> label and description -> tooltip
  780. # otherwise description -> lavel
  781. if p.get('label','') != '':
  782. title = text_beautify(p['label'])
  783. tooltip = text_beautify(p['description'], width = -1)
  784. else:
  785. title = text_beautify(p['description'])
  786. tooltip = None
  787. prompt = p.get('prompt', '')
  788. # title sizer (description, name, type)
  789. if (len(p.get('values', [])) > 0) and \
  790. p.get('multiple', False) and \
  791. p.get('gisprompt', False) == False and \
  792. p.get('type', '') == 'string':
  793. title_txt = wx.StaticBox(parent = which_panel, id = wx.ID_ANY)
  794. else:
  795. title_sizer = wx.BoxSizer(wx.HORIZONTAL)
  796. title_txt = wx.StaticText(parent = which_panel)
  797. if p['key_desc']:
  798. ltype = ','.join(p['key_desc'])
  799. else:
  800. ltype = p['type']
  801. # red star for required options
  802. if p.get('required', False):
  803. required_txt = wx.StaticText(parent=which_panel, label="*")
  804. required_txt.SetForegroundColour(wx.RED)
  805. required_txt.SetToolTipString(_("This option is required"))
  806. else:
  807. required_txt = wx.StaticText(parent=which_panel, label="")
  808. rtitle_txt = wx.StaticText(parent = which_panel,
  809. label = '(' + p['name'] + '=' + ltype + ')')
  810. title_sizer.Add(item = title_txt, proportion = 0,
  811. flag = wx.LEFT | wx.TOP | wx.EXPAND, border = 5)
  812. title_sizer.Add(item = required_txt, proportion=1,
  813. flag = wx.EXPAND, border=0)
  814. title_sizer.Add(item = rtitle_txt, proportion = 0,
  815. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  816. which_sizer.Add(item = title_sizer, proportion = 0,
  817. flag = wx.EXPAND)
  818. self.label_id.append(title_txt.GetId())
  819. # title expansion
  820. if p.get('multiple', False) and len(p.get('values','')) == 0:
  821. title = _("[multiple]") + " " + title
  822. if p.get('value','') == '' :
  823. p['value'] = p.get('default','')
  824. if (len(p.get('values', [])) > 0):
  825. valuelist = map(str, p.get('values',[]))
  826. valuelist_desc = map(unicode, p.get('values_desc',[]))
  827. required_text = "*" if p.get('required', False) else ""
  828. if p.get('multiple', False) and \
  829. p.get('gisprompt',False) == False and \
  830. p.get('type', '') == 'string':
  831. title_txt.SetLabel(" %s:%s (%s=%s) " % (title, required_text, p['name'], p['type']))
  832. stSizer = wx.StaticBoxSizer(box = title_txt, orient = wx.VERTICAL)
  833. if valuelist_desc:
  834. hSizer = wx.FlexGridSizer(cols = 1, vgap = 1)
  835. else:
  836. hSizer = wx.FlexGridSizer(cols = 6, vgap = 1, hgap = 1)
  837. isEnabled = {}
  838. # copy default values
  839. if p['value'] == '':
  840. p['value'] = p.get('default', '')
  841. for defval in p.get('value', '').split(','):
  842. isEnabled[ defval ] = 'yes'
  843. # for multi checkboxes, this is an array of all wx IDs
  844. # for each individual checkbox
  845. p[ 'wxId' ] = list()
  846. idx = 0
  847. for val in valuelist:
  848. try:
  849. label = valuelist_desc[idx]
  850. except IndexError:
  851. label = val
  852. chkbox = wx.CheckBox(parent = which_panel,
  853. label = text_beautify(label))
  854. p[ 'wxId' ].append(chkbox.GetId())
  855. if val in isEnabled:
  856. chkbox.SetValue(True)
  857. hSizer.Add(item = chkbox, proportion = 0)
  858. chkbox.Bind(wx.EVT_CHECKBOX, self.OnUpdateSelection)
  859. chkbox.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxMulti)
  860. idx += 1
  861. stSizer.Add(item = hSizer, proportion = 0,
  862. flag = wx.ADJUST_MINSIZE | wx.ALL, border = 1)
  863. which_sizer.Add(item = stSizer, proportion = 0,
  864. flag = wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, border = 5)
  865. elif p.get('gisprompt', False) is False:
  866. if len(valuelist) == 1: # -> textctrl
  867. title_txt.SetLabel("%s (%s %s):" % (title, _('valid range'),
  868. str(valuelist[0])))
  869. if p.get('type', '') == 'integer' and \
  870. not p.get('multiple', False):
  871. # for multiple integers use textctrl instead of spinsctrl
  872. try:
  873. minValue, maxValue = map(int, valuelist[0].rsplit('-', 1))
  874. except ValueError:
  875. minValue = -1e6
  876. maxValue = 1e6
  877. txt2 = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY, size = globalvar.DIALOG_SPIN_SIZE,
  878. min = minValue, max = maxValue)
  879. style = wx.BOTTOM | wx.LEFT
  880. else:
  881. txt2 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  882. style = wx.EXPAND | wx.BOTTOM | wx.LEFT
  883. value = self._getValue(p)
  884. # parameter previously set
  885. if value:
  886. if isinstance(txt2, wx.SpinCtrl):
  887. txt2.SetValue(int(value))
  888. else:
  889. txt2.SetValue(value)
  890. which_sizer.Add(item = txt2, proportion = 0,
  891. flag = style, border = 5)
  892. p['wxId'] = [ txt2.GetId(), ]
  893. txt2.Bind(wx.EVT_TEXT, self.OnSetValue)
  894. else:
  895. title_txt.SetLabel(title + ':')
  896. value = self._getValue(p)
  897. if p['name'] == 'icon': # symbols
  898. bitmap = wx.Bitmap(os.path.join(globalvar.SYMBDIR, value) + '.png')
  899. bb = wx.BitmapButton(parent = which_panel, id = wx.ID_ANY,
  900. bitmap = bitmap)
  901. iconLabel = wx.StaticText(parent = which_panel, id = wx.ID_ANY)
  902. iconLabel.SetLabel(value)
  903. p['value'] = value
  904. p['wxId'] = [bb.GetId(), iconLabel.GetId()]
  905. bb.Bind(wx.EVT_BUTTON, self.OnSetSymbol)
  906. this_sizer = wx.BoxSizer(wx.HORIZONTAL)
  907. this_sizer.Add(item = bb, proportion = 0,
  908. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  909. this_sizer.Add(item = iconLabel, proportion = 0,
  910. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.ALIGN_CENTER_VERTICAL, border = 5)
  911. which_sizer.Add(item = this_sizer, proportion = 0,
  912. flag = wx.ADJUST_MINSIZE, border = 0)
  913. else:
  914. # list of values (combo)
  915. cb = wx.ComboBox(parent=which_panel, id=wx.ID_ANY, value=p.get('default',''),
  916. size=globalvar.DIALOG_COMBOBOX_SIZE,
  917. choices=valuelist, style=wx.CB_DROPDOWN)
  918. if value:
  919. cb.SetValue(value) # parameter previously set
  920. which_sizer.Add(item = cb, proportion = 0,
  921. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  922. p['wxId'] = [cb.GetId(),]
  923. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  924. cb.Bind(wx.EVT_TEXT, self.OnSetValue)
  925. if p.get('guidependency', ''):
  926. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  927. # text entry
  928. if (p.get('type','string') in ('string','integer','float')
  929. and len(p.get('values',[])) == 0
  930. and p.get('gisprompt',False) == False
  931. and p.get('prompt','') != 'color'):
  932. title_txt.SetLabel(title + ':')
  933. if p.get('multiple', False) or \
  934. p.get('type', 'string') == 'string' or \
  935. len(p.get('key_desc', [])) > 1:
  936. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''))
  937. value = self._getValue(p)
  938. if value:
  939. # parameter previously set
  940. txt3.SetValue(str(value))
  941. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  942. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  943. elif p.get('type', '') == 'integer':
  944. minValue = -1e9
  945. maxValue = 1e9
  946. value = self._getValue(p)
  947. txt3 = wx.SpinCtrl(parent = which_panel, value = p.get('default', ''),
  948. size = globalvar.DIALOG_SPIN_SIZE,
  949. min = minValue, max = maxValue)
  950. if value:
  951. txt3.SetValue(int(value)) # parameter previously set
  952. txt3.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  953. style = wx.BOTTOM | wx.LEFT | wx.RIGHT
  954. else: # float
  955. txt3 = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  956. validator = FloatValidator())
  957. style = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT
  958. value = self._getValue(p)
  959. if value:
  960. txt3.SetValue(str(value)) # parameter previously set
  961. txt3.Bind(wx.EVT_TEXT, self.OnSetValue)
  962. which_sizer.Add(item = txt3, proportion = 0,
  963. flag = style, border = 5)
  964. p['wxId'] = [ txt3.GetId(), ]
  965. #
  966. # element selection tree combobox (maps, icons, regions, etc.)
  967. #
  968. if p.get('gisprompt', False):
  969. title_txt.SetLabel(title + ':')
  970. # GIS element entry
  971. if p.get('prompt','') not in ('color',
  972. 'subgroup',
  973. 'sigfile',
  974. 'separator',
  975. 'dbdriver',
  976. 'dbname',
  977. 'dbtable',
  978. 'dbcolumn',
  979. 'layer',
  980. 'location',
  981. 'mapset',
  982. 'dbase',
  983. 'coords',
  984. 'file',
  985. 'dir',
  986. 'colortable',
  987. 'barscale',
  988. 'northarrow'):
  989. multiple = p.get('multiple', False)
  990. if p.get('age', '') == 'new':
  991. mapsets = [grass.gisenv()['MAPSET'],]
  992. else:
  993. mapsets = None
  994. if self.task.name in ('r.proj', 'v.proj') \
  995. and p.get('name', '') == 'input':
  996. selection = gselect.ProjSelect(parent = which_panel,
  997. isRaster = self.task.name == 'r.proj')
  998. p['wxId'] = [ selection.GetId(), ]
  999. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1000. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1001. else:
  1002. elem = p.get('element', None)
  1003. # hack for t.* modules
  1004. if elem in ('stds', 'map'):
  1005. orig_elem = elem
  1006. type_param = self.task.get_param('type', element = 'name', raiseError = False)
  1007. if type_param:
  1008. elem = type_param.get('default', None)
  1009. # for t.(un)register:
  1010. maps_param = self.task.get_param('maps', element = 'name', raiseError = False)
  1011. if maps_param and orig_elem == 'stds':
  1012. element_dict = {'raster': 'strds', 'vector': 'stvds', 'raster_3d': 'str3ds'}
  1013. elem = element_dict[type_param.get('default')]
  1014. if self._giface and hasattr(self._giface, "_model"):
  1015. extraItems = {_('Graphical Modeler') : self._giface.GetLayerList(p.get('prompt'))}
  1016. else:
  1017. extraItems = None
  1018. selection = gselect.Select(parent = which_panel, id = wx.ID_ANY,
  1019. size = globalvar.DIALOG_GSELECT_SIZE,
  1020. type = elem, multiple = multiple, nmaps = len(p.get('key_desc', [])),
  1021. mapsets = mapsets, fullyQualified = p.get('age', 'old') == 'old',
  1022. extraItems = extraItems)
  1023. value = self._getValue(p)
  1024. if value:
  1025. selection.SetValue(value)
  1026. formatSelector = True
  1027. # A gselect.Select is a combobox with two children: a textctl and a popupwindow;
  1028. # we target the textctl here
  1029. textWin = selection.GetTextCtrl()
  1030. if globalvar.CheckWxVersion([3]):
  1031. p['wxId'] = [selection.GetId(), ]
  1032. else:
  1033. p['wxId'] = [textWin.GetId(), ]
  1034. if prompt != 'vector':
  1035. self.FindWindowById(p['wxId'][0]).Bind(wx.EVT_TEXT, self.OnSetValue)
  1036. if prompt == 'vector':
  1037. win = self.FindWindowById(p['wxId'][0])
  1038. # handlers should be bound in this order
  1039. # OnUpdateSelection depends on calling OnSetValue first which is bad
  1040. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1041. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1042. # if formatSelector and p.get('age', 'old') == 'old':
  1043. # # OGR supported (read-only)
  1044. # self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
  1045. # self.hsizer.Add(item = selection,
  1046. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1047. # border = 5)
  1048. # # format (native / ogr)
  1049. # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY,
  1050. # label = " %s " % _("Format"),
  1051. # style = wx.RA_SPECIFY_ROWS,
  1052. # choices = [_("Native / Linked OGR"), _("Direct OGR")])
  1053. # if p.get('value', '').lower().rfind('@ogr') > -1:
  1054. # rbox.SetSelection(1)
  1055. # rbox.SetName('VectorFormat')
  1056. # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat)
  1057. # self.hsizer.Add(item = rbox,
  1058. # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1059. # wx.RIGHT | wx.ALIGN_TOP,
  1060. # border = 5)
  1061. # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True,
  1062. # default = 'dir',
  1063. # exclude = ['file'])
  1064. # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection)
  1065. # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue)
  1066. # ogrSelection.SetName('OgrSelect')
  1067. # ogrSelection.Hide()
  1068. # which_sizer.Add(item = self.hsizer, proportion = 0)
  1069. # p['wxId'].append(rbox.GetId())
  1070. # p['wxId'].append(ogrSelection.GetId())
  1071. # for win in ogrSelection.GetDsnWin():
  1072. # p['wxId'].append(win.GetId())
  1073. # else:
  1074. which_sizer.Add(item = selection, proportion = 0,
  1075. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1076. border = 5)
  1077. elif prompt == 'group':
  1078. win = self.FindWindowById(p['wxId'][0])
  1079. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1080. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1081. which_sizer.Add(item = selection, proportion = 0,
  1082. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1083. border = 5)
  1084. else:
  1085. if prompt in ('stds', 'strds', 'stvds', 'str3ds'):
  1086. showButton = True
  1087. try:
  1088. # if matplotlib is there
  1089. from timeline import frame
  1090. showButton = True
  1091. except ImportError:
  1092. showButton = False
  1093. else:
  1094. showButton = False
  1095. if showButton:
  1096. iconTheme = UserSettings.Get(group='appearance', key='iconTheme', subkey='type')
  1097. bitmap = wx.Bitmap(os.path.join(globalvar.ICONDIR, iconTheme, 'map-info.png'))
  1098. bb = wx.BitmapButton(parent=which_panel, bitmap=bitmap)
  1099. bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool)
  1100. bb.SetToolTipString(_("Show graphical representation of temporal extent of dataset(s) ."))
  1101. p['wxId'].append(bb.GetId())
  1102. hSizer = wx.BoxSizer(wx.HORIZONTAL)
  1103. hSizer.Add(item=selection, proportion=0,
  1104. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1105. border=5)
  1106. hSizer.Add(item=bb, proportion=0,
  1107. flag=wx.EXPAND|wx.BOTTOM | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1108. border=5)
  1109. which_sizer.Add(hSizer)
  1110. else:
  1111. which_sizer.Add(item=selection, proportion=0,
  1112. flag=wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1113. border=5)
  1114. # subgroup
  1115. elif prompt == 'subgroup':
  1116. selection = gselect.SubGroupSelect(parent = which_panel)
  1117. p['wxId'] = [ selection.GetId() ]
  1118. selection.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1119. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1120. which_sizer.Add(item = selection, proportion = 0,
  1121. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1122. border = 5)
  1123. # sigrature file
  1124. elif prompt == 'sigfile':
  1125. selection = gselect.SignatureSelect(parent = which_panel, element = p.get('element', 'sig'))
  1126. p['wxId'] = [ selection.GetId() ]
  1127. selection.Bind(wx.EVT_TEXT, self.OnSetValue)
  1128. selection.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1129. which_sizer.Add(item = selection, proportion = 0,
  1130. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1131. border = 5)
  1132. # separator
  1133. elif prompt == 'separator':
  1134. win = gselect.SeparatorSelect(parent = which_panel)
  1135. value = self._getValue(p)
  1136. win.SetValue(value)
  1137. p['wxId'] = [ win.GetId() ]
  1138. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1139. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1140. which_sizer.Add(item = win, proportion = 0,
  1141. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_CENTER_VERTICAL,
  1142. border = 5)
  1143. # layer, dbdriver, dbname, dbcolumn, dbtable entry
  1144. elif prompt in ('dbdriver',
  1145. 'dbname',
  1146. 'dbtable',
  1147. 'dbcolumn',
  1148. 'layer',
  1149. 'location',
  1150. 'mapset',
  1151. 'dbase'):
  1152. if p.get('multiple', 'no') == 'yes':
  1153. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1154. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1155. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1156. else:
  1157. value = self._getValue(p)
  1158. if prompt == 'layer':
  1159. if p.get('element', 'layer') == 'layer_all':
  1160. all = True
  1161. else:
  1162. all = False
  1163. if p.get('age', 'old') == 'old':
  1164. win = gselect.LayerSelect(parent = which_panel,
  1165. all = all,
  1166. default = p['default'])
  1167. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1168. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1169. win.SetValue(str(value)) # default or previously set value
  1170. else:
  1171. win = wx.SpinCtrl(parent = which_panel, id = wx.ID_ANY,
  1172. min = 1, max = 100, initial = int(p['default']))
  1173. win.Bind(wx.EVT_SPINCTRL, self.OnSetValue)
  1174. win.SetValue(int(value)) # default or previously set value
  1175. p['wxId'] = [ win.GetId() ]
  1176. elif prompt == 'dbdriver':
  1177. win = gselect.DriverSelect(parent = which_panel,
  1178. choices = p.get('values', []),
  1179. value = value)
  1180. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1181. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1182. elif prompt == 'dbname':
  1183. win = gselect.DatabaseSelect(parent = which_panel,
  1184. value = value)
  1185. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1186. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1187. elif prompt == 'dbtable':
  1188. if p.get('age', 'old') == 'old':
  1189. win = gselect.TableSelect(parent = which_panel)
  1190. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1191. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1192. else:
  1193. win = wx.TextCtrl(parent = which_panel, value = p.get('default',''),
  1194. size = globalvar.DIALOG_TEXTCTRL_SIZE)
  1195. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1196. elif prompt == 'dbcolumn':
  1197. win = gselect.ColumnSelect(parent = which_panel,
  1198. value = value,
  1199. param = p,
  1200. multiple = p.get('multiple', False))
  1201. # A gselect.ColumnSelect is a combobox
  1202. # with two children: a textctl and a
  1203. # popupwindow; we target the textctl here
  1204. textWin = win.GetTextCtrl()
  1205. p['wxId'] = [ textWin.GetId(), ]
  1206. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1207. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1208. elif prompt == 'location':
  1209. win = gselect.LocationSelect(parent = which_panel,
  1210. value = value)
  1211. win.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1212. win.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1213. elif prompt == 'mapset':
  1214. if p.get('age', 'old') == 'old':
  1215. new = False
  1216. else:
  1217. new = True
  1218. win = gselect.MapsetSelect(parent = which_panel,
  1219. value = value, new = new,
  1220. multiple = p.get('multiple', False))
  1221. textWin = win.GetTextCtrl()
  1222. p['wxId'] = [ textWin.GetId(), win.GetId() ]
  1223. textWin.Bind(wx.EVT_TEXT, self.OnSetValue)
  1224. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1225. elif prompt == 'dbase':
  1226. win = gselect.DbaseSelect(parent = which_panel,
  1227. changeCallback = self.OnSetValue)
  1228. win.Bind(wx.EVT_TEXT, self.OnUpdateSelection)
  1229. p['wxId'] = [ win.GetChildren()[1].GetId() ]
  1230. if 'wxId' not in p:
  1231. try:
  1232. p['wxId'] = [ win.GetId(), ]
  1233. except AttributeError:
  1234. pass
  1235. flags = wx.BOTTOM | wx.LEFT | wx.RIGHT
  1236. if prompt == 'dbname':
  1237. flags |= wx.EXPAND
  1238. which_sizer.Add(item = win, proportion = 0,
  1239. flag = flags, border = 5)
  1240. # color entry
  1241. elif prompt == 'color':
  1242. default_color = (200,200,200)
  1243. label_color = _("Select Color")
  1244. if p.get('default','') != '':
  1245. default_color, label_color = utils.color_resolve(p['default'])
  1246. if p.get('value','') != '' and p.get('value','') != 'none': # parameter previously set
  1247. if not p.get('multiple', False):
  1248. default_color, label_color = utils.color_resolve(p['value'])
  1249. if p.get('element', '') == 'color_none' or p.get('multiple', False):
  1250. this_sizer = wx.BoxSizer(orient = wx.HORIZONTAL)
  1251. else:
  1252. this_sizer = which_sizer
  1253. colorSize = 150
  1254. # For color selectors, this is a three-member array, holding the IDs of
  1255. # the color picker, the text control for multiple colors (or None),
  1256. # and either a "transparent" checkbox or None
  1257. p['wxId'] = [None] * 3
  1258. if p.get('multiple', False):
  1259. txt = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY)
  1260. this_sizer.Add(item = txt, proportion = 1,
  1261. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.TOP, border = 5)
  1262. txt.Bind(wx.EVT_TEXT, self.OnSetValue)
  1263. if p.get('value', ''):
  1264. txt.SetValue(p['value'])
  1265. colorSize = 40
  1266. label_color = ''
  1267. p['wxId'][1] = txt.GetId()
  1268. which_sizer.Add(this_sizer, flag = wx.EXPAND | wx.RIGHT, border = 5)
  1269. btn_colour = csel.ColourSelect(parent = which_panel, id = wx.ID_ANY,
  1270. label = label_color, colour = default_color,
  1271. pos = wx.DefaultPosition, size = (colorSize, 32))
  1272. this_sizer.Add(item = btn_colour, proportion = 0,
  1273. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1274. btn_colour.Bind(csel.EVT_COLOURSELECT, self.OnColorChange)
  1275. p['wxId'][0] = btn_colour.GetId()
  1276. if p.get('element', '') == 'color_none':
  1277. none_check = wx.CheckBox(which_panel, wx.ID_ANY, _("Transparent"))
  1278. if p.get('value','') == "none":
  1279. none_check.SetValue(True)
  1280. else:
  1281. none_check.SetValue(False)
  1282. this_sizer.Add(item = none_check, proportion = 0,
  1283. flag = wx.ADJUST_MINSIZE | wx.LEFT | wx.RIGHT | wx.TOP, border = 5)
  1284. which_sizer.Add(this_sizer)
  1285. none_check.Bind(wx.EVT_CHECKBOX, self.OnColorChange)
  1286. p['wxId'][2] = none_check.GetId()
  1287. # file selector
  1288. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'file':
  1289. if p.get('age', 'new') == 'new':
  1290. fmode = wx.FD_SAVE
  1291. else:
  1292. fmode = wx.FD_OPEN
  1293. # check wildcard
  1294. try:
  1295. fExt = os.path.splitext(p.get('key_desc', ['*.*'])[0])[1]
  1296. except:
  1297. fExt = None
  1298. if not fExt:
  1299. fMask = '*'
  1300. else:
  1301. fMask = '%s files (*%s)|*%s|Files (*)|*' % (fExt[1:].upper(), fExt, fExt)
  1302. fbb = filebrowse.FileBrowseButton(parent = which_panel, id = wx.ID_ANY, fileMask = fMask,
  1303. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1304. dialogTitle = _('Choose %s') % \
  1305. p.get('description', _('file')).lower(),
  1306. buttonText = _('Browse'),
  1307. startDirectory = os.getcwd(), fileMode = fmode,
  1308. changeCallback = self.OnSetValue)
  1309. value = self._getValue(p)
  1310. if value:
  1311. fbb.SetValue(value) # parameter previously set
  1312. which_sizer.Add(item = fbb, proportion = 0,
  1313. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1314. # A file browse button is a combobox with two children:
  1315. # a textctl and a button;
  1316. # we have to target the button here
  1317. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1318. if p.get('age', 'new') == 'old' and \
  1319. p.get('prompt', '') == 'file' and p.get('element', '') == 'file' and \
  1320. UserSettings.Get(group = 'cmd', key = 'interactiveInput', subkey = 'enabled'):
  1321. # widget for interactive input
  1322. ifbb = wx.TextCtrl(parent = which_panel, id = wx.ID_ANY,
  1323. style = wx.TE_MULTILINE,
  1324. size = (-1, 75))
  1325. if p.get('value', '') and os.path.isfile(p['value']):
  1326. f = open(p['value'])
  1327. ifbb.SetValue(''.join(f.readlines()))
  1328. f.close()
  1329. ifbb.Bind(wx.EVT_TEXT, self.OnFileText)
  1330. btnLoad = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Load"))
  1331. btnLoad.SetToolTipString(_("Load and edit content of a file"))
  1332. btnLoad.Bind(wx.EVT_BUTTON, self.OnFileLoad)
  1333. btnSave = wx.Button(parent = which_panel, id = wx.ID_ANY, label = _("&Save as"))
  1334. btnSave.SetToolTipString(_("Save content to a file for further use"))
  1335. btnSave.Bind(wx.EVT_BUTTON, self.OnFileSave)
  1336. fileContentLabel = wx.StaticText(parent=which_panel,
  1337. id=wx.ID_ANY,
  1338. label=_('or enter values directly:'))
  1339. fileContentLabel.SetToolTipString(
  1340. _("Enter file content directly instead of specifying"
  1341. " a file."
  1342. " Temporary file will be automatically created."))
  1343. which_sizer.Add(item=fileContentLabel,
  1344. proportion = 0,
  1345. flag = wx.EXPAND | wx.RIGHT | wx.LEFT | wx.BOTTOM, border = 5)
  1346. which_sizer.Add(item = ifbb, proportion = 1,
  1347. flag = wx.EXPAND | wx.RIGHT | wx.LEFT, border = 5)
  1348. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  1349. btnSizer.Add(item = btnLoad, proportion = 0,
  1350. flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 10)
  1351. btnSizer.Add(item = btnSave, proportion = 0,
  1352. flag = wx.ALIGN_RIGHT)
  1353. which_sizer.Add(item = btnSizer, proportion = 0,
  1354. flag = wx.ALIGN_RIGHT | wx.RIGHT | wx.TOP, border = 5)
  1355. p['wxId'].append(ifbb.GetId())
  1356. p['wxId'].append(btnLoad.GetId())
  1357. p['wxId'].append(btnSave.GetId())
  1358. # directory selector
  1359. elif p.get('prompt','') != 'color' and p.get('prompt', '') == 'dir':
  1360. fbb = filebrowse.DirBrowseButton(parent = which_panel, id = wx.ID_ANY,
  1361. size = globalvar.DIALOG_GSELECT_SIZE, labelText = '',
  1362. dialogTitle = _('Choose %s') % \
  1363. p.get('description', _('Directory')),
  1364. buttonText = _('Browse'),
  1365. startDirectory = os.getcwd(),
  1366. changeCallback = self.OnSetValue)
  1367. value = self._getValue(p)
  1368. if value:
  1369. fbb.SetValue(value) # parameter previously set
  1370. which_sizer.Add(item = fbb, proportion = 0,
  1371. flag = wx.EXPAND | wx.RIGHT, border = 5)
  1372. # A file browse button is a combobox with two children:
  1373. # a textctl and a button;
  1374. # we have to target the button here
  1375. p['wxId'] = [ fbb.GetChildren()[1].GetId() ]
  1376. # interactive inserting of coordinates from map window
  1377. elif prompt == 'coords':
  1378. # interactive inserting if layer manager is accessible
  1379. if self._giface:
  1380. win = gselect.CoordinatesSelect(parent = which_panel,
  1381. giface = self._giface,
  1382. multiple = p.get('multiple', False),
  1383. param = p)
  1384. p['wxId'] = [win.GetTextWin().GetId()]
  1385. win.GetTextWin().Bind(wx.EVT_TEXT, self.OnSetValue)
  1386. # bind closing event because destructor is not working properly
  1387. if hasattr(self.parent, 'dialogClosing'):
  1388. self.parent.dialogClosing.connect(win.OnClose)
  1389. # normal text field
  1390. else:
  1391. win = wx.TextCtrl(parent = which_panel)
  1392. p['wxId'] = [win.GetId()]
  1393. win.Bind(wx.EVT_TEXT, self.OnSetValue)
  1394. which_sizer.Add(item = win,
  1395. proportion = 0,
  1396. flag = wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
  1397. border = 5)
  1398. elif prompt in ('colortable', 'barscale', 'northarrow'):
  1399. if prompt == 'colortable':
  1400. cb = ColorTablesComboBox(parent=which_panel, value=p.get('default',''),
  1401. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1402. choices=valuelist)
  1403. elif prompt == 'barscale':
  1404. cb = BarscalesComboBox(parent=which_panel, value=p.get('default',''),
  1405. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1406. choices=valuelist)
  1407. elif prompt == 'northarrow':
  1408. cb = NArrowsComboBox(parent=which_panel, value=p.get('default',''),
  1409. size=globalvar.DIALOG_COMBOBOX_SIZE,
  1410. choices=valuelist)
  1411. value = self._getValue(p)
  1412. if value:
  1413. cb.SetValue(value) # parameter previously set
  1414. which_sizer.Add(item = cb, proportion = 0,
  1415. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT, border = 5)
  1416. p['wxId'] = [cb.GetId(), cb.GetTextCtrl().GetId()]
  1417. cb.Bind(wx.EVT_COMBOBOX, self.OnSetValue)
  1418. cb.GetTextCtrl().Bind(wx.EVT_TEXT, self.OnSetValue)
  1419. if p.get('guidependency', ''):
  1420. cb.Bind(wx.EVT_COMBOBOX, self.OnUpdateSelection)
  1421. if self.parent.GetName() == 'MainFrame' and (self._giface and hasattr(self._giface, "_model")):
  1422. parChk = wx.CheckBox(parent = which_panel, id = wx.ID_ANY,
  1423. label = _("Parameterized in model"))
  1424. parChk.SetName('ModelParam')
  1425. parChk.SetValue(p.get('parameterized', False))
  1426. if 'wxId' in p:
  1427. p['wxId'].append(parChk.GetId())
  1428. else:
  1429. p['wxId'] = [ parChk.GetId() ]
  1430. parChk.Bind(wx.EVT_CHECKBOX, self.OnSetValue)
  1431. which_sizer.Add(item = parChk, proportion = 0,
  1432. flag = wx.LEFT, border = 20)
  1433. if title_txt is not None:
  1434. # create tooltip if given
  1435. if len(p['values_desc']) > 0:
  1436. if tooltip:
  1437. tooltip += 2 * os.linesep
  1438. else:
  1439. tooltip = ''
  1440. if len(p['values']) == len(p['values_desc']):
  1441. for i in range(len(p['values'])):
  1442. tooltip += p['values'][i] + ': ' + p['values_desc'][i] + os.linesep
  1443. tooltip.strip(os.linesep)
  1444. if tooltip:
  1445. title_txt.SetToolTipString(tooltip)
  1446. if p == first_param:
  1447. if 'wxId' in p and len(p['wxId']) > 0:
  1448. win = self.FindWindowById(p['wxId'][0])
  1449. win.SetFocus()
  1450. #
  1451. # set widget relations for OnUpdateSelection
  1452. #
  1453. pMap = None
  1454. pLayer = []
  1455. pDriver = None
  1456. pDatabase = None
  1457. pTable = None
  1458. pColumn = []
  1459. pGroup = None
  1460. pSubGroup = None
  1461. pSigFile = []
  1462. pDbase = None
  1463. pLocation = None
  1464. pMapset = None
  1465. for p in self.task.params:
  1466. guidep = p.get('guidependency', '')
  1467. if guidep:
  1468. # fixed options dependency defined
  1469. options = guidep.split(',')
  1470. for opt in options:
  1471. pOpt = self.task.get_param(opt, element = 'name', raiseError = False)
  1472. if pOpt and id:
  1473. if 'wxId-bind' not in p:
  1474. p['wxId-bind'] = list()
  1475. p['wxId-bind'] += pOpt['wxId']
  1476. continue
  1477. if p.get('gisprompt', False) == False:
  1478. continue
  1479. prompt = p.get('prompt', '')
  1480. if prompt in ('raster', 'vector'):
  1481. name = p.get('name', '')
  1482. if name in ('map', 'input'):
  1483. pMap = p
  1484. elif prompt == 'layer':
  1485. pLayer.append(p)
  1486. elif prompt == 'dbcolumn':
  1487. pColumn.append(p)
  1488. elif prompt == 'dbdriver':
  1489. pDriver = p
  1490. elif prompt == 'dbname':
  1491. pDatabase = p
  1492. elif prompt == 'dbtable':
  1493. pTable = p
  1494. elif prompt == 'group':
  1495. pGroup = p
  1496. elif prompt == 'subgroup':
  1497. pSubGroup = p
  1498. elif prompt == 'sigfile':
  1499. pSigFile.append(p)
  1500. elif prompt == 'dbase':
  1501. pDbase = p
  1502. elif prompt == 'location':
  1503. pLocation = p
  1504. elif prompt == 'mapset':
  1505. pMapset = p
  1506. # collect ids
  1507. pColumnIds = []
  1508. for p in pColumn:
  1509. pColumnIds += p['wxId']
  1510. pLayerIds = []
  1511. for p in pLayer:
  1512. pLayerIds += p['wxId']
  1513. pSigFileIds = []
  1514. for p in pSigFile:
  1515. pSigFileIds += p['wxId']
  1516. # set wxId-bindings
  1517. if pMap:
  1518. pMap['wxId-bind'] = []
  1519. if pLayer:
  1520. pMap['wxId-bind'] += pLayerIds
  1521. pMap['wxId-bind'] += copy.copy(pColumnIds)
  1522. if pLayer:
  1523. for p in pLayer:
  1524. p['wxId-bind'] = copy.copy(pColumnIds)
  1525. if pDriver and pTable:
  1526. pDriver['wxId-bind'] = pTable['wxId']
  1527. if pDatabase and pTable:
  1528. pDatabase['wxId-bind'] = pTable['wxId']
  1529. if pTable and pColumnIds:
  1530. pTable['wxId-bind'] = pColumnIds
  1531. if pGroup and pSubGroup:
  1532. if pSigFile:
  1533. pGroup['wxId-bind'] = pSigFileIds + pSubGroup['wxId']
  1534. pSubGroup['wxId-bind'] = pSigFileIds
  1535. else:
  1536. pGroup['wxId-bind'] = pSubGroup['wxId']
  1537. if pDbase and pLocation:
  1538. pDbase['wxId-bind'] = pLocation['wxId']
  1539. if pLocation and pMapset:
  1540. pLocation['wxId-bind'] = pMapset['wxId']
  1541. if pLocation and pMapset and pMap:
  1542. # pLocation['wxId-bind'] += pMap['wxId']
  1543. pMapset['wxId-bind'] = pMap['wxId']
  1544. #
  1545. # determine panel size
  1546. #
  1547. maxsizes = (0, 0)
  1548. for section in sections:
  1549. tab[section].SetSizer(tabsizer[section])
  1550. tabsizer[section].Fit(tab[section])
  1551. tab[section].Layout()
  1552. minsecsizes = tabsizer[section].GetSize()
  1553. maxsizes = map(lambda x: max(maxsizes[x], minsecsizes[x]), (0, 1))
  1554. # TODO: be less arbitrary with these 600
  1555. self.panelMinHeight = 100
  1556. self.constrained_size = (min(600, maxsizes[0]) + 25, min(400, maxsizes[1]) + 25)
  1557. for section in sections:
  1558. tab[section].SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1559. # add pages to notebook
  1560. imageList = wx.ImageList(16, 16)
  1561. self.notebook.AssignImageList(imageList)
  1562. for section in sections:
  1563. self.notebook.AddPage(page = tab[section], text = section, name = section)
  1564. index = self.AddBitmapToImageList(section, imageList)
  1565. if index >= 0:
  1566. self.notebook.SetPageImage(section, index)
  1567. # are we running from command line?
  1568. ### add 'command output' tab regardless standalone dialog
  1569. if self.parent.GetName() == "MainFrame" and self.parent.get_dcmd is None:
  1570. from core.gconsole import GConsole, EVT_CMD_RUN, EVT_CMD_DONE
  1571. from gui_core.goutput import GConsoleWindow
  1572. self._gconsole = GConsole(guiparent = self.notebook, giface = self._giface)
  1573. self.goutput = GConsoleWindow(parent = self.notebook, gconsole = self._gconsole, margin = False)
  1574. self._gconsole.Bind(EVT_CMD_RUN,
  1575. lambda event:
  1576. self._switchPageHandler(event=event, notification=Notification.MAKE_VISIBLE))
  1577. self._gconsole.Bind(EVT_CMD_DONE,
  1578. lambda event:
  1579. self._switchPageHandler(event = event, notification=Notification.RAISE_WINDOW))
  1580. self.outpage = self.notebook.AddPage(page = self.goutput, text = _("Command output"), name = 'output')
  1581. else:
  1582. self.goutput = None
  1583. self._gconsole = None
  1584. self.manualTab = HelpPanel(parent = self.notebook, command = self.task.get_name())
  1585. if not self.manualTab.GetFile():
  1586. self.manualTab.Hide()
  1587. else:
  1588. self.notebook.AddPage(page = self.manualTab, text = _("Manual"), name = 'manual')
  1589. index = self.AddBitmapToImageList(section = 'manual', imageList = imageList)
  1590. if index >= 0:
  1591. self.notebook.SetPageImage('manual', index)
  1592. if self.manualTab.IsLoaded():
  1593. self.manualTab.SetMinSize((self.constrained_size[0], self.panelMinHeight))
  1594. self.notebook.SetSelection(0)
  1595. panelsizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
  1596. self.SetSizer(panelsizer)
  1597. panelsizer.Fit(self.notebook)
  1598. self.Bind(EVT_DIALOG_UPDATE, self.OnUpdateDialog)
  1599. def _getValue(self, p):
  1600. """Get value or default value of given parameter
  1601. :param p: parameter directory
  1602. """
  1603. if p.get('value', '') != '':
  1604. return p['value']
  1605. return p.get('default', '')
  1606. def OnFileLoad(self, event):
  1607. """Load file to interactive input"""
  1608. me = event.GetId()
  1609. win = dict()
  1610. for p in self.task.params:
  1611. if 'wxId' in p and me in p['wxId']:
  1612. win['file'] = self.FindWindowById(p['wxId'][0])
  1613. win['text'] = self.FindWindowById(p['wxId'][1])
  1614. break
  1615. if not win:
  1616. return
  1617. path = win['file'].GetValue()
  1618. if not path:
  1619. gcmd.GMessage(parent = self,
  1620. message = _("Nothing to load."))
  1621. return
  1622. data = ''
  1623. try:
  1624. f = open(path, "r")
  1625. except IOError as e:
  1626. gcmd.GError(parent = self, showTraceback = False,
  1627. message = _("Unable to load file.\n\nReason: %s") % e)
  1628. return
  1629. try:
  1630. data = f.read()
  1631. finally:
  1632. f.close()
  1633. win['text'].SetValue(data)
  1634. def OnFileSave(self, event):
  1635. """Save interactive input to the file"""
  1636. wId = event.GetId()
  1637. win = {}
  1638. for p in self.task.params:
  1639. if wId in p.get('wxId', []):
  1640. win['file'] = self.FindWindowById(p['wxId'][0])
  1641. win['text'] = self.FindWindowById(p['wxId'][1])
  1642. break
  1643. if not win:
  1644. return
  1645. text = win['text'].GetValue()
  1646. if not text:
  1647. gcmd.GMessage(parent = self,
  1648. message = _("Nothing to save."))
  1649. return
  1650. dlg = wx.FileDialog(parent = self,
  1651. message = _("Save input as..."),
  1652. defaultDir = os.getcwd(),
  1653. style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
  1654. if dlg.ShowModal() == wx.ID_OK:
  1655. path = dlg.GetPath()
  1656. enc = locale.getdefaultlocale()[1]
  1657. f = codecs.open(path, encoding = enc, mode = 'w', errors='replace')
  1658. try:
  1659. f.write(text + os.linesep)
  1660. finally:
  1661. f.close()
  1662. win['file'].SetValue(path)
  1663. dlg.Destroy()
  1664. def OnFileText(self, event):
  1665. """File input interactively entered"""
  1666. text = event.GetString()
  1667. p = self.task.get_param(value = event.GetId(), element = 'wxId', raiseError = False)
  1668. if not p:
  1669. return # should not happen
  1670. win = self.FindWindowById(p['wxId'][0])
  1671. if text:
  1672. filename = win.GetValue()
  1673. if not filename or filename == p['default']: # m.proj has - as default
  1674. filename = grass.tempfile()
  1675. win.SetValue(filename)
  1676. enc = locale.getdefaultlocale()[1]
  1677. f = codecs.open(filename, encoding = enc, mode = 'w', errors='replace')
  1678. try:
  1679. f.write(text)
  1680. if text[-1] != os.linesep:
  1681. f.write(os.linesep)
  1682. finally:
  1683. f.close()
  1684. else:
  1685. win.SetValue('')
  1686. def OnVectorFormat(self, event):
  1687. """Change vector format (native / ogr).
  1688. Currently unused.
  1689. """
  1690. sel = event.GetSelection()
  1691. idEvent = event.GetId()
  1692. p = self.task.get_param(value = idEvent, element = 'wxId', raiseError = False)
  1693. if not p:
  1694. return # should not happen
  1695. # detect windows
  1696. winNative = None
  1697. winOgr = None
  1698. for id in p['wxId']:
  1699. if id == idEvent:
  1700. continue
  1701. name = self.FindWindowById(id).GetName()
  1702. if name == 'Select':
  1703. winNative = self.FindWindowById(id + 1) # fix the mystery (also in nviz_tools.py)
  1704. elif name == 'OgrSelect':
  1705. winOgr = self.FindWindowById(id)
  1706. # enable / disable widgets & update values
  1707. rbox = self.FindWindowByName('VectorFormat')
  1708. self.hsizer.Remove(rbox)
  1709. if sel == 0: # -> native
  1710. winOgr.Hide()
  1711. self.hsizer.Remove(winOgr)
  1712. self.hsizer.Add(item = winNative,
  1713. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1714. border = 5)
  1715. winNative.Show()
  1716. p['value'] = winNative.GetValue()
  1717. elif sel == 1: # -> OGR
  1718. sizer = wx.BoxSizer(wx.VERTICAL)
  1719. winNative.Hide()
  1720. self.hsizer.Remove(winNative)
  1721. sizer.Add(item = winOgr)
  1722. winOgr.Show()
  1723. p['value'] = winOgr.GetDsn()
  1724. self.hsizer.Add(item = sizer,
  1725. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP,
  1726. border = 5)
  1727. self.hsizer.Add(item = rbox,
  1728. flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT |
  1729. wx.RIGHT | wx.ALIGN_TOP,
  1730. border = 5)
  1731. self.hsizer.Layout()
  1732. self.Layout()
  1733. self.OnUpdateValues()
  1734. self.OnUpdateSelection(event)
  1735. def OnUpdateDialog(self, event):
  1736. for fn, kwargs in event.data.iteritems():
  1737. fn(**kwargs)
  1738. self.parent.updateValuesHook()
  1739. def OnVerbosity(self, event):
  1740. """Verbosity level changed"""
  1741. verbose = self.FindWindowById(self.task.get_flag('verbose')['wxId'][0])
  1742. quiet = self.FindWindowById(self.task.get_flag('quiet')['wxId'][0])
  1743. if event.IsChecked():
  1744. if event.GetId() == verbose.GetId():
  1745. if quiet.IsChecked():
  1746. quiet.SetValue(False)
  1747. self.task.get_flag('quiet')['value'] = False
  1748. else:
  1749. if verbose.IsChecked():
  1750. verbose.SetValue(False)
  1751. self.task.get_flag('verbose')['value'] = False
  1752. event.Skip()
  1753. def OnPageChange(self, event):
  1754. if not event:
  1755. sel = self.notebook.GetSelection()
  1756. else:
  1757. sel = event.GetSelection()
  1758. idx = self.notebook.GetPageIndexByName('manual')
  1759. if idx > -1 and sel == idx:
  1760. # calling LoadPage() is strangely time-consuming (only first call)
  1761. # FIXME: move to helpPage.__init__()
  1762. if not self.manualTab.IsLoaded():
  1763. wx.Yield()
  1764. self.manualTab.LoadPage()
  1765. self.Layout()
  1766. if event:
  1767. # skip is needed for wx.Notebook on Windows
  1768. event.Skip()
  1769. # this is needed for dialogs launched from layer manager
  1770. # event is somehow propagated?
  1771. event.StopPropagation()
  1772. def _switchPageHandler(self, event, notification):
  1773. self._switchPage(notification=notification)
  1774. event.Skip()
  1775. def _switchPage(self, notification):
  1776. """Manages @c 'output' notebook page according to event notification."""
  1777. if notification == Notification.HIGHLIGHT:
  1778. self.notebook.HighlightPageByName('output')
  1779. if notification == Notification.MAKE_VISIBLE:
  1780. self.notebook.SetSelectionByName('output')
  1781. if notification == Notification.RAISE_WINDOW:
  1782. self.notebook.SetSelectionByName('output')
  1783. self.SetFocus()
  1784. self.Raise()
  1785. def OnColorChange(self, event):
  1786. myId = event.GetId()
  1787. for p in self.task.params:
  1788. if 'wxId' in p and myId in p['wxId']:
  1789. multiple = p['wxId'][1] is not None # multiple colors
  1790. hasTansp = p['wxId'][2] is not None
  1791. if multiple:
  1792. # selected color is added at the end of textCtrl
  1793. colorchooser = wx.FindWindowById(p['wxId'][0])
  1794. new_color = colorchooser.GetValue()[:]
  1795. new_label = utils.rgb2str.get(new_color, ':'.join(map(str, new_color)))
  1796. textCtrl = wx.FindWindowById(p['wxId'][1])
  1797. val = textCtrl.GetValue()
  1798. sep = ','
  1799. if val and val[-1] != sep:
  1800. val += sep
  1801. val += new_label
  1802. textCtrl.SetValue(val)
  1803. p[ 'value' ] = val
  1804. elif hasTansp and wx.FindWindowById(p['wxId'][2]).GetValue():
  1805. p[ 'value' ] = 'none'
  1806. else:
  1807. colorchooser = wx.FindWindowById(p['wxId'][0])
  1808. new_color = colorchooser.GetValue()[:]
  1809. # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple
  1810. # under wx2.8.1
  1811. new_label = utils.rgb2str.get(new_color, ':'.join(map(str,new_color)))
  1812. colorchooser.SetLabel(new_label)
  1813. colorchooser.SetColour(new_color)
  1814. colorchooser.Refresh()
  1815. p[ 'value' ] = colorchooser.GetLabel()
  1816. self.OnUpdateValues()
  1817. def OnUpdateValues(self, event = None):
  1818. """If we were part of a richer interface, report back the
  1819. current command being built.
  1820. This method should be set by the parent of this panel if
  1821. needed. It's a hook, actually. Beware of what is 'self' in
  1822. the method def, though. It will be called with no arguments.
  1823. """
  1824. pass
  1825. def OnCheckBoxMulti(self, event):
  1826. """Fill the values as a ','-separated string according to
  1827. current status of the checkboxes.
  1828. """
  1829. me = event.GetId()
  1830. theParam = None
  1831. for p in self.task.params:
  1832. if 'wxId' in p and me in p['wxId']:
  1833. theParam = p
  1834. myIndex = p['wxId'].index(me)
  1835. # Unpack current value list
  1836. currentValues = {}
  1837. for isThere in theParam.get('value', '').split(','):
  1838. currentValues[isThere] = 1
  1839. theValue = theParam['values'][myIndex]
  1840. if event.Checked():
  1841. currentValues[ theValue ] = 1
  1842. else:
  1843. del currentValues[ theValue ]
  1844. # Keep the original order, so that some defaults may be recovered
  1845. currentValueList = []
  1846. for v in theParam['values']:
  1847. if v in currentValues:
  1848. currentValueList.append(v)
  1849. # Pack it back
  1850. theParam['value'] = ','.join(currentValueList)
  1851. self.OnUpdateValues()
  1852. event.Skip()
  1853. def OnSetValue(self, event):
  1854. """Retrieve the widget value and set the task value field
  1855. accordingly.
  1856. Use for widgets that have a proper GetValue() method, i.e. not
  1857. for selectors.
  1858. """
  1859. myId = event.GetId()
  1860. me = wx.FindWindowById(myId)
  1861. name = me.GetName()
  1862. found = False
  1863. for porf in self.task.params + self.task.flags:
  1864. if 'wxId' not in porf:
  1865. continue
  1866. if myId in porf['wxId']:
  1867. found = True
  1868. break
  1869. if not found:
  1870. return
  1871. if name == 'GdalSelect':
  1872. porf['value'] = event.dsn
  1873. elif name == 'ModelParam':
  1874. porf['parameterized'] = me.IsChecked()
  1875. else:
  1876. if isinstance(me, wx.SpinCtrl):
  1877. porf['value'] = str(me.GetValue())
  1878. elif isinstance(me, wx.ComboBox):
  1879. porf['value'] = me.GetValue()
  1880. elif isinstance(me, wx.Choice):
  1881. porf['value'] = me.GetStringSelection()
  1882. else:
  1883. porf['value'] = me.GetValue()
  1884. self.OnUpdateValues(event)
  1885. event.Skip()
  1886. def OnSetSymbol(self, event):
  1887. """Shows dialog for symbol selection"""
  1888. myId = event.GetId()
  1889. for p in self.task.params:
  1890. if 'wxId' in p and myId in p['wxId']:
  1891. from gui_core.dialogs import SymbolDialog
  1892. dlg = SymbolDialog(self, symbolPath = globalvar.SYMBDIR,
  1893. currentSymbol = p['value'])
  1894. if dlg.ShowModal() == wx.ID_OK:
  1895. img = dlg.GetSelectedSymbolPath()
  1896. p['value'] = dlg.GetSelectedSymbolName()
  1897. bitmapButton = wx.FindWindowById(p['wxId'][0])
  1898. label = wx.FindWindowById(p['wxId'][1])
  1899. bitmapButton.SetBitmapLabel(wx.Bitmap(img + '.png'))
  1900. label.SetLabel(p['value'])
  1901. self.OnUpdateValues(event)
  1902. dlg.Destroy()
  1903. def OnTimelineTool(self, event):
  1904. """Show Timeline Tool with dataset(s) from gselect.
  1905. .. todo::
  1906. update from gselect automatically
  1907. """
  1908. myId = event.GetId()
  1909. for p in self.task.params:
  1910. if 'wxId' in p and myId in p['wxId']:
  1911. select = self.FindWindowById(p['wxId'][0])
  1912. if not select.GetValue():
  1913. gcmd.GMessage(parent=self, message=_("No dataset given."))
  1914. return
  1915. datasets = select.GetValue().split(',')
  1916. from timeline import frame
  1917. frame.run(parent=self, datasets=datasets)
  1918. def OnUpdateSelection(self, event):
  1919. """Update dialog (layers, tables, columns, etc.)
  1920. """
  1921. if not hasattr(self.parent, "updateThread"):
  1922. if event:
  1923. event.Skip()
  1924. return
  1925. if event:
  1926. self.parent.updateThread.Update(UpdateDialog,
  1927. self,
  1928. event,
  1929. event.GetId(),
  1930. self.task)
  1931. else:
  1932. self.parent.updateThread.Update(UpdateDialog,
  1933. self,
  1934. None,
  1935. None,
  1936. self.task)
  1937. def createCmd(self, ignoreErrors = False, ignoreRequired = False):
  1938. """Produce a command line string (list) or feeding into GRASS.
  1939. :param ignoreErrors: True then it will return whatever has been
  1940. built so far, even though it would not be
  1941. a correct command for GRASS
  1942. """
  1943. try:
  1944. cmd = self.task.get_cmd(ignoreErrors = ignoreErrors,
  1945. ignoreRequired = ignoreRequired)
  1946. except ValueError as err:
  1947. dlg = wx.MessageDialog(parent = self,
  1948. message = gcmd.DecodeString(str(err)),
  1949. caption = _("Error in %s") % self.task.name,
  1950. style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  1951. dlg.ShowModal()
  1952. dlg.Destroy()
  1953. cmd = None
  1954. return cmd
  1955. def OnSize(self, event):
  1956. width = event.GetSize()[0]
  1957. fontsize = self.GetFont().GetPointSize()
  1958. text_width = max(width / (fontsize - 3), 70)
  1959. for id in self.label_id:
  1960. win = self.FindWindowById(id)
  1961. label = win.GetLabel()
  1962. label_new = '\n'.join(textwrap.wrap(label, text_width))
  1963. win.SetLabel(label_new)
  1964. event.Skip()
  1965. def AddBitmapToImageList(self, section, imageList):
  1966. iconTheme = UserSettings.Get(group = 'appearance', key = 'iconTheme', subkey = 'type')
  1967. iconSectionDict = {'manual': os.path.join(globalvar.ICONDIR, iconTheme, 'help.png')}
  1968. if section in iconSectionDict.keys():
  1969. image = wx.Image(iconSectionDict[section]).Scale(16, 16, wx.IMAGE_QUALITY_HIGH)
  1970. idx = imageList.Add(wx.BitmapFromImage(image))
  1971. return idx
  1972. return -1
  1973. class GUI:
  1974. def __init__(self, parent = None, giface = None, show = True, modal = False,
  1975. centreOnParent = False, checkError = False):
  1976. """Parses GRASS commands when module is imported and used from
  1977. Layer Manager.
  1978. """
  1979. self.parent = parent
  1980. self.show = show
  1981. self.modal = modal
  1982. self._giface = giface
  1983. self.centreOnParent = centreOnParent
  1984. self.checkError = checkError
  1985. self.grass_task = None
  1986. self.cmd = list()
  1987. global _blackList
  1988. if self.parent:
  1989. _blackList['enabled'] = True
  1990. else:
  1991. _blackList['enabled'] = False
  1992. def GetCmd(self):
  1993. """Get validated command"""
  1994. return self.cmd
  1995. def ParseCommand(self, cmd, completed = None):
  1996. """Parse command
  1997. Note: cmd is given as list
  1998. If command is given with options, return validated cmd list:
  1999. - add key name for first parameter if not given
  2000. - change mapname to mapname@mapset
  2001. """
  2002. dcmd_params = {}
  2003. if completed == None:
  2004. get_dcmd = None
  2005. layer = None
  2006. dcmd_params = None
  2007. else:
  2008. get_dcmd = completed[0]
  2009. layer = completed[1]
  2010. if completed[2]:
  2011. dcmd_params.update(completed[2])
  2012. # parse the interface decription
  2013. try:
  2014. global _blackList
  2015. self.grass_task = gtask.parse_interface(cmd[0],
  2016. blackList = _blackList)
  2017. except (grass.ScriptError, ValueError) as e:
  2018. raise gcmd.GException(e.value)
  2019. # if layer parameters previously set, re-insert them into dialog
  2020. if completed is not None:
  2021. if 'params' in dcmd_params:
  2022. self.grass_task.params = dcmd_params['params']
  2023. if 'flags' in dcmd_params:
  2024. self.grass_task.flags = dcmd_params['flags']
  2025. err = list()
  2026. # update parameters if needed && validate command
  2027. if len(cmd) > 1:
  2028. i = 0
  2029. cmd_validated = [cmd[0]]
  2030. for option in cmd[1:]:
  2031. if option[0] == '-': # flag
  2032. if len(option) == 1: # catch typo like 'g.proj - w'
  2033. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  2034. if option[1] == '-':
  2035. self.grass_task.set_flag(option[2:], True)
  2036. else:
  2037. self.grass_task.set_flag(option[1], True)
  2038. cmd_validated.append(option)
  2039. else: # parameter
  2040. try:
  2041. key, value = option.split('=', 1)
  2042. except ValueError:
  2043. if self.grass_task.firstParam:
  2044. if i == 0: # add key name of first parameter if not given
  2045. key = self.grass_task.firstParam
  2046. value = option
  2047. else:
  2048. raise gcmd.GException, _("Unable to parse command '%s'") % ' '.join(cmd)
  2049. else:
  2050. continue
  2051. task = self.grass_task.get_param(key, raiseError = False)
  2052. if not task:
  2053. err.append(_("%(cmd)s: parameter '%(key)s' not available") % \
  2054. { 'cmd' : cmd[0],
  2055. 'key' : key })
  2056. continue
  2057. multiple = task['multiple']
  2058. element = task['element']
  2059. # to filter out g.copy, g.rename
  2060. key_desc = task['key_desc']
  2061. # do we need to find mapset for each of multiple maps?
  2062. if element in ['cell', 'vector'] and not multiple and len(key_desc) != 2:
  2063. # mapname -> mapname@mapset
  2064. try:
  2065. name, mapset = value.split('@')
  2066. except ValueError:
  2067. mapset = grass.find_file(value, element)['mapset']
  2068. curr_mapset = grass.gisenv()['MAPSET']
  2069. if mapset and mapset != curr_mapset:
  2070. value = value + '@' + mapset
  2071. self.grass_task.set_param(key, value)
  2072. cmd_validated.append(key + '=' + value)
  2073. i += 1
  2074. # update original command list
  2075. cmd = cmd_validated
  2076. if self.show is not None:
  2077. self.mf = TaskFrame(parent = self.parent, giface = self._giface,
  2078. task_description = self.grass_task,
  2079. get_dcmd = get_dcmd, layer = layer)
  2080. else:
  2081. self.mf = None
  2082. if get_dcmd is not None:
  2083. # update only propwin reference
  2084. get_dcmd(dcmd = None, layer = layer, params = None,
  2085. propwin = self.mf)
  2086. if self.show is not None:
  2087. self.mf.notebookpanel.OnUpdateSelection(None)
  2088. if self.show is True:
  2089. if self.parent and self.centreOnParent:
  2090. self.mf.CentreOnParent()
  2091. else:
  2092. self.mf.CenterOnScreen()
  2093. self.mf.Show(self.show)
  2094. self.mf.MakeModal(self.modal)
  2095. else:
  2096. self.mf.OnApply(None)
  2097. self.cmd = cmd
  2098. if self.checkError:
  2099. return self.grass_task, err
  2100. else:
  2101. return self.grass_task
  2102. def GetCommandInputMapParamKey(self, cmd):
  2103. """Get parameter key for input raster/vector map
  2104. :param cmd: module name
  2105. :return: parameter key
  2106. :return: None on failure
  2107. """
  2108. # parse the interface decription
  2109. if not self.grass_task:
  2110. tree = etree.fromstring(gtask.get_interface_description(cmd))
  2111. self.grass_task = gtask.processTask(tree).get_task()
  2112. for p in self.grass_task.params:
  2113. if p.get('name', '') in ('input', 'map'):
  2114. age = p.get('age', '')
  2115. prompt = p.get('prompt', '')
  2116. element = p.get('element', '')
  2117. if age == 'old' and \
  2118. element in ('cell', 'grid3', 'vector') and \
  2119. prompt in ('raster', '3d-raster', 'vector'):
  2120. return p.get('name', None)
  2121. return None
  2122. class GrassGUIApp(wx.App):
  2123. """Stand-alone GRASS command GUI
  2124. """
  2125. def __init__(self, grass_task):
  2126. self.grass_task = grass_task
  2127. wx.App.__init__(self, False)
  2128. def OnInit(self):
  2129. msg = self.grass_task.get_error_msg()
  2130. if msg:
  2131. gcmd.GError(msg + '\n\n' +
  2132. _('Try to set up GRASS_ADDON_PATH or GRASS_ADDON_BASE variable.'))
  2133. return True
  2134. self.mf = TaskFrame(parent = None, giface = None, task_description = self.grass_task)
  2135. self.mf.CentreOnScreen()
  2136. self.mf.Show(True)
  2137. self.SetTopWindow(self.mf)
  2138. return True
  2139. USAGE_MESSAGE = """Usage:
  2140. {name} <grass module>
  2141. {name} <full path to file>
  2142. python {name} <grass module>
  2143. Test:
  2144. python {name} test
  2145. python {name} g.region
  2146. python {name} "g.region -p"
  2147. python {name} temporal/t.list/t.list.py"""
  2148. if __name__ == "__main__":
  2149. if len(sys.argv) == 1:
  2150. sys.exit(_(USAGE_MESSAGE).format(name=sys.argv[0]))
  2151. if sys.argv[1] != 'test':
  2152. q = wx.LogNull()
  2153. from core.debug import Debug
  2154. Debug.msg(1, "forms.py called using command: %s" % sys.argv[1])
  2155. cmd = utils.split(sys.argv[1])
  2156. task = gtask.grassTask(cmd[0])
  2157. task.set_options(cmd[1:])
  2158. Debug.msg(1, "forms.py opening form for: %s" % task.get_cmd(ignoreErrors=True, ignoreRequired=True))
  2159. app = GrassGUIApp(task)
  2160. app.MainLoop()
  2161. else: #Test
  2162. # Test grassTask from within a GRASS session
  2163. if os.getenv("GISBASE") is not None:
  2164. task = gtask.grassTask("d.vect")
  2165. task.get_param('map')['value'] = "map_name"
  2166. task.get_flag('i')['value'] = True
  2167. task.get_param('layer')['value'] = 1
  2168. task.get_param('label_bcolor')['value'] = "red"
  2169. # the default parameter display is added automatically
  2170. assert ' '.join(task.get_cmd()) == "d.vect -i map=map_name layer=1 display=shape label_bcolor=red"
  2171. print "Creation of task successful"
  2172. # Test interface building with handmade grassTask,
  2173. # possibly outside of a GRASS session.
  2174. print "Now creating a module dialog (task frame)"
  2175. task = gtask.grassTask()
  2176. task.name = "TestTask"
  2177. task.description = "This is an artificial grassTask() object intended for testing purposes."
  2178. task.keywords = ["grass","test","task"]
  2179. task.params = [
  2180. {
  2181. "name" : "text",
  2182. "description" : "Descriptions go into tooltips if labels are present, like this one",
  2183. "label" : "Enter some text",
  2184. "key_desc": ["value"],
  2185. "values_desc": []
  2186. },{
  2187. "name" : "hidden_text",
  2188. "description" : "This text should not appear in the form",
  2189. "hidden" : True,
  2190. "key_desc": ["value"],
  2191. "values_desc": []
  2192. },{
  2193. "name" : "text_default",
  2194. "description" : "Enter text to override the default",
  2195. "default" : "default text",
  2196. "key_desc": ["value"],
  2197. "values_desc": []
  2198. },{
  2199. "name" : "text_prefilled",
  2200. "description" : "You should see a friendly welcome message here",
  2201. "value" : "hello, world",
  2202. "key_desc": ["value"],
  2203. "values_desc": []
  2204. },{
  2205. "name" : "plain_color",
  2206. "description" : "This is a plain color, and it is a compulsory parameter",
  2207. "required" : False,
  2208. "gisprompt" : True,
  2209. "prompt" : "color",
  2210. "key_desc": ["value"],
  2211. "values_desc": []
  2212. },{
  2213. "name" : "transparent_color",
  2214. "description" : "This color becomes transparent when set to none",
  2215. "guisection" : "tab",
  2216. "gisprompt" : True,
  2217. "prompt" : "color",
  2218. "key_desc": ["value"],
  2219. "values_desc": []
  2220. },{
  2221. "name" : "multi",
  2222. "description" : "A multiple selection",
  2223. 'default': u'red,green,blue',
  2224. 'gisprompt': False,
  2225. 'guisection': 'tab',
  2226. 'multiple': u'yes',
  2227. 'type': u'string',
  2228. 'value': '',
  2229. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2230. "key_desc": ["value"],
  2231. "values_desc": []
  2232. },{
  2233. "name" : "single",
  2234. "description" : "A single multiple-choice selection",
  2235. 'values': ['red', 'green', u'yellow', u'blue', u'purple', u'other'],
  2236. "guisection" : "tab",
  2237. "key_desc": ["value"],
  2238. "values_desc": []
  2239. },{
  2240. "name" : "large_multi",
  2241. "description" : "A large multiple selection",
  2242. "gisprompt" : False,
  2243. "multiple" : "yes",
  2244. # values must be an array of strings
  2245. "values" : utils.str2rgb.keys() + map(str, utils.str2rgb.values()),
  2246. "key_desc": ["value"],
  2247. "values_desc": []
  2248. },{
  2249. "name" : "a_file",
  2250. "description" : "A file selector",
  2251. "gisprompt" : True,
  2252. "element" : "file",
  2253. "key_desc": ["value"],
  2254. "values_desc": []
  2255. }
  2256. ]
  2257. task.flags = [
  2258. {
  2259. "name" : "a",
  2260. "description" : "Some flag, will appear in Main since it is required",
  2261. "required" : True,
  2262. "value" : False,
  2263. "suppress_required": False
  2264. },{
  2265. "name" : "b",
  2266. "description" : "pre-filled flag, will appear in options since it is not required",
  2267. "value" : True,
  2268. "suppress_required": False
  2269. },{
  2270. "name" : "hidden_flag",
  2271. "description" : "hidden flag, should not be changeable",
  2272. "hidden" : "yes",
  2273. "value" : True,
  2274. "suppress_required": False
  2275. }
  2276. ]
  2277. q = wx.LogNull()
  2278. GrassGUIApp(task).MainLoop()