forms.py 127 KB

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