forms.py 112 KB

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