forms.py 123 KB

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