forms.py 126 KB

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