forms.py 120 KB

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