forms.py 124 KB

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