frame.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764
  1. """!
  2. @package psmap.frame
  3. @brief GUI for ps.map
  4. Classes:
  5. - frame::PsMapFrame
  6. - frame::PsMapBufferedWindow
  7. (C) 2011 by Anna Kratochvilova, and the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Anna Kratochvilova <kratochanna gmail.com> (bachelor's project)
  11. @author Martin Landa <landa.martin gmail.com> (mentor)
  12. """
  13. import os
  14. import sys
  15. import textwrap
  16. import Queue
  17. from math import sin, cos, pi
  18. try:
  19. import Image as PILImage
  20. havePILImage = True
  21. except ImportError:
  22. havePILImage = False
  23. if __name__ == "__main__":
  24. sys.path.append(os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython'))
  25. from core import globalvar
  26. import wx
  27. try:
  28. import wx.lib.agw.flatnotebook as fnb
  29. except ImportError:
  30. import wx.lib.flatnotebook as fnb
  31. import grass.script as grass
  32. from gui_core.menu import Menu
  33. from gui_core.goutput import CmdThread, EVT_CMD_DONE
  34. from psmap.toolbars import PsMapToolbar
  35. from core.gcmd import RunCommand, GError, GMessage
  36. from gui_core.forms import GUI
  37. from psmap.menudata import PsMapData
  38. from psmap.dialogs import *
  39. class PsMapFrame(wx.Frame):
  40. def __init__(self, parent = None, id = wx.ID_ANY,
  41. title = _("GRASS GIS Cartographic Composer"), **kwargs):
  42. """!Main window of ps.map GUI
  43. @param parent parent window
  44. @param id window id
  45. @param title window title
  46. @param kwargs wx.Frames' arguments
  47. """
  48. self.parent = parent
  49. wx.Frame.__init__(self, parent = parent, id = id, title = title, name = "PsMap", **kwargs)
  50. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  51. #menubar
  52. self.menubar = Menu(parent = self, data = PsMapData())
  53. self.SetMenuBar(self.menubar)
  54. #toolbar
  55. self.toolbar = PsMapToolbar(parent = self)
  56. self.SetToolBar(self.toolbar)
  57. self.actionOld = self.toolbar.action['id']
  58. self.iconsize = (16, 16)
  59. #satusbar
  60. self.statusbar = self.CreateStatusBar(number = 1)
  61. # mouse attributes -- position on the screen, begin and end of
  62. # dragging, and type of drawing
  63. self.mouse = {
  64. 'begin': [0, 0], # screen coordinates
  65. 'end' : [0, 0],
  66. 'use' : "pointer",
  67. }
  68. # available cursors
  69. self.cursors = {
  70. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  71. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  72. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  73. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  74. }
  75. # pen and brush
  76. self.pen = {
  77. 'paper': wx.Pen(colour = "BLACK", width = 1),
  78. 'margins': wx.Pen(colour = "GREY", width = 1),
  79. 'map': wx.Pen(colour = wx.Color(86, 122, 17), width = 2),
  80. 'rasterLegend': wx.Pen(colour = wx.Color(219, 216, 4), width = 2),
  81. 'vectorLegend': wx.Pen(colour = wx.Color(219, 216, 4), width = 2),
  82. 'mapinfo': wx.Pen(colour = wx.Color(5, 184, 249), width = 2),
  83. 'scalebar': wx.Pen(colour = wx.Color(150, 150, 150), width = 2),
  84. 'image': wx.Pen(colour = wx.Color(255, 150, 50), width = 2),
  85. 'northArrow': wx.Pen(colour = wx.Color(200, 200, 200), width = 2),
  86. 'box': wx.Pen(colour = 'RED', width = 2, style = wx.SHORT_DASH),
  87. 'select': wx.Pen(colour = 'BLACK', width = 1, style = wx.SHORT_DASH),
  88. 'resize': wx.Pen(colour = 'BLACK', width = 1)
  89. }
  90. self.brush = {
  91. 'paper': wx.WHITE_BRUSH,
  92. 'margins': wx.TRANSPARENT_BRUSH,
  93. 'map': wx.Brush(wx.Color(151, 214, 90)),
  94. 'rasterLegend': wx.Brush(wx.Color(250, 247, 112)),
  95. 'vectorLegend': wx.Brush(wx.Color(250, 247, 112)),
  96. 'mapinfo': wx.Brush(wx.Color(127, 222, 252)),
  97. 'scalebar': wx.Brush(wx.Color(200, 200, 200)),
  98. 'image': wx.Brush(wx.Color(255, 200, 50)),
  99. 'northArrow': wx.Brush(wx.Color(255, 255, 255)),
  100. 'box': wx.TRANSPARENT_BRUSH,
  101. 'select':wx.TRANSPARENT_BRUSH,
  102. 'resize': wx.BLACK_BRUSH
  103. }
  104. # list of objects to draw
  105. self.objectId = []
  106. # instructions
  107. self.instruction = Instruction(parent = self, objectsToDraw = self.objectId)
  108. # open dialogs
  109. self.openDialogs = dict()
  110. self.pageId = wx.NewId()
  111. #current page of flatnotebook
  112. self.currentPage = 0
  113. #canvas for draft mode
  114. self.canvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, pen = self.pen,
  115. brush = self.brush, cursors = self.cursors,
  116. instruction = self.instruction, openDialogs = self.openDialogs,
  117. pageId = self.pageId, objectId = self.objectId,
  118. preview = False)
  119. self.canvas.SetCursor(self.cursors["default"])
  120. self.getInitMap()
  121. # image path
  122. env = grass.gisenv()
  123. self.imgName = os.path.join(env['GISDBASE'], env['LOCATION_NAME'], env['MAPSET'], '.tmp', 'tmpImage.png')
  124. #canvas for preview
  125. self.previewCanvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, cursors = self.cursors,
  126. pen = self.pen, brush = self.brush, preview = True)
  127. # set WIND_OVERRIDE
  128. grass.use_temp_region()
  129. # create queues
  130. self.requestQ = Queue.Queue()
  131. self.resultQ = Queue.Queue()
  132. # thread
  133. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  134. self._layout()
  135. self.SetMinSize(wx.Size(750, 600))
  136. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
  137. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  138. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  139. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  140. if not havePILImage:
  141. wx.CallAfter(self._showErrMsg)
  142. def _showErrMsg(self):
  143. """!Show error message (missing preview)
  144. """
  145. GError(parent = self,
  146. message = _("Python Imaging Library is not available.\n"
  147. "'Preview' functionality won't work."),
  148. showTraceback = False)
  149. def _layout(self):
  150. """!Do layout
  151. """
  152. mainSizer = wx.BoxSizer(wx.VERTICAL)
  153. if globalvar.hasAgw:
  154. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  155. agwStyle = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  156. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  157. else:
  158. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  159. style = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  160. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  161. #self.book = fnb.FlatNotebook(self, wx.ID_ANY, style = fnb.FNB_BOTTOM)
  162. self.book.AddPage(self.canvas, "Draft mode")
  163. self.book.AddPage(self.previewCanvas, "Preview")
  164. self.book.SetSelection(0)
  165. mainSizer.Add(self.book,1, wx.EXPAND)
  166. self.SetSizer(mainSizer)
  167. mainSizer.Fit(self)
  168. def InstructionFile(self):
  169. """!Creates mapping instructions"""
  170. return str(self.instruction)
  171. def OnPSFile(self, event):
  172. """!Generate PostScript"""
  173. filename = self.getFile(wildcard = "PostScript (*.ps)|*.ps|Encapsulated PostScript (*.eps)|*.eps")
  174. if filename:
  175. self.PSFile(filename)
  176. def OnPsMapDialog(self, event):
  177. """!Launch ps.map dialog
  178. """
  179. GUI(parent = self).ParseCommand(cmd = ['ps.map'])
  180. def OnPDFFile(self, event):
  181. """!Generate PDF from PS with ps2pdf if available"""
  182. try:
  183. p = grass.Popen(["ps2pdf"], stderr = grass.PIPE)
  184. p.stderr.close()
  185. except OSError:
  186. GMessage(parent = self,
  187. message = _("Program ps2pdf is not available. Please install it first to create PDF."))
  188. return
  189. filename = self.getFile(wildcard = "PDF (*.pdf)|*.pdf")
  190. if filename:
  191. self.PSFile(filename, pdf = True)
  192. def OnPreview(self, event):
  193. """!Run ps.map and show result"""
  194. self.PSFile()
  195. def PSFile(self, filename = None, pdf = False):
  196. """!Create temporary instructions file and run ps.map with output = filename"""
  197. instrFile = grass.tempfile()
  198. instrFileFd = open(instrFile, mode = 'w')
  199. instrFileFd.write(self.InstructionFile())
  200. instrFileFd.flush()
  201. instrFileFd.close()
  202. temp = False
  203. regOld = grass.region()
  204. if pdf:
  205. pdfname = filename
  206. else:
  207. pdfname = None
  208. #preview or pdf
  209. if not filename or (filename and pdf):
  210. temp = True
  211. filename = grass.tempfile()
  212. if not pdf: # lower resolution for preview
  213. if self.instruction.FindInstructionByType('map'):
  214. mapId = self.instruction.FindInstructionByType('map').id
  215. SetResolution(dpi = 100, width = self.instruction[mapId]['rect'][2],
  216. height = self.instruction[mapId]['rect'][3])
  217. cmd = ['ps.map', '--overwrite']
  218. if os.path.splitext(filename)[1] == '.eps':
  219. cmd.append('-e')
  220. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  221. cmd.append('-r')
  222. cmd.append('input=%s' % instrFile)
  223. cmd.append('output=%s' % filename)
  224. if pdf:
  225. self.SetStatusText(_('Generating PDF...'), 0)
  226. elif not temp:
  227. self.SetStatusText(_('Generating PostScript...'), 0)
  228. else:
  229. self.SetStatusText(_('Generating preview...'), 0)
  230. self.cmdThread.RunCmd(cmd, userData = {'instrFile' : instrFile, 'filename' : filename,
  231. 'pdfname' : pdfname, 'temp' : temp, 'regionOld' : regOld})
  232. def OnCmdDone(self, event):
  233. """!ps.map process finished"""
  234. if event.returncode != 0:
  235. GMessage(parent = self,
  236. message = _("Ps.map exited with return code %s") % event.returncode)
  237. grass.try_remove(event.userData['instrFile'])
  238. if event.userData['temp']:
  239. grass.try_remove(event.userData['filename'])
  240. return
  241. if event.userData['pdfname']:
  242. try:
  243. proc = grass.Popen(['ps2pdf', '-dPDFSETTINGS=/prepress', '-r1200',
  244. event.userData['filename'], event.userData['pdfname']])
  245. ret = proc.wait()
  246. if ret > 0:
  247. GMessage(parent = self,
  248. message = _("ps2pdf exited with return code %s") % ret)
  249. except OSError, e:
  250. GError(parent = self,
  251. message = _("Program ps2pdf is not available. Please install it to create PDF.\n\n %s") % e)
  252. # show preview only when user doesn't want to create ps or pdf
  253. if havePILImage and event.userData['temp'] and not event.userData['pdfname']:
  254. RunCommand('g.region', cols = event.userData['regionOld']['cols'], rows = event.userData['regionOld']['rows'])
  255. ## wx.BusyInfo does not display the message
  256. ## busy = wx.BusyInfo(message = "Generating preview, wait please", parent = self)
  257. try:
  258. im = PILImage.open(event.userData['filename'])
  259. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  260. im = im.rotate(270)
  261. im.save(self.imgName, format = 'png')
  262. except IOError, e:
  263. GError(parent = self,
  264. message = _("Unable to generate preview. %s") % e)
  265. rect = self.previewCanvas.ImageRect()
  266. self.previewCanvas.image = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  267. self.previewCanvas.DrawImage(rect = rect)
  268. ## busy.Destroy()
  269. self.SetStatusText(_('Preview generated'), 0)
  270. self.book.SetSelection(1)
  271. self.currentPage = 1
  272. grass.try_remove(event.userData['instrFile'])
  273. if event.userData['temp']:
  274. grass.try_remove(event.userData['filename'])
  275. def getFile(self, wildcard):
  276. suffix = []
  277. for filter in wildcard.split('|')[1::2]:
  278. s = filter.strip('*').split('.')[1]
  279. if s:
  280. s = '.' + s
  281. suffix.append(s)
  282. raster = self.instruction.FindInstructionByType('raster')
  283. if raster:
  284. rasterId = raster.id
  285. else:
  286. rasterId = None
  287. if rasterId and self.instruction[rasterId]['raster']:
  288. mapName = self.instruction[rasterId]['raster'].split('@')[0] + suffix[0]
  289. else:
  290. mapName = ''
  291. filename = ''
  292. dlg = wx.FileDialog(self, message = _("Save file as"), defaultDir = "",
  293. defaultFile = mapName, wildcard = wildcard,
  294. style = wx.CHANGE_DIR | wx.SAVE | wx.OVERWRITE_PROMPT)
  295. if dlg.ShowModal() == wx.ID_OK:
  296. filename = dlg.GetPath()
  297. suffix = suffix[dlg.GetFilterIndex()]
  298. if not os.path.splitext(filename)[1]:
  299. filename = filename + suffix
  300. elif os.path.splitext(filename)[1] != suffix and suffix != '':
  301. filename = os.path.splitext(filename)[0] + suffix
  302. dlg.Destroy()
  303. return filename
  304. def OnInstructionFile(self, event):
  305. filename = self.getFile(wildcard = "*.psmap|*.psmap|Text file(*.txt)|*.txt|All files(*.*)|*.*")
  306. if filename:
  307. instrFile = open(filename, "w")
  308. instrFile.write(self.InstructionFile())
  309. instrFile.close()
  310. def OnLoadFile(self, event):
  311. """!Load file and read instructions"""
  312. #find file
  313. filename = ''
  314. dlg = wx.FileDialog(self, message = "Find instructions file", defaultDir = "",
  315. defaultFile = '', wildcard = "All files (*.*)|*.*",
  316. style = wx.CHANGE_DIR|wx.OPEN)
  317. if dlg.ShowModal() == wx.ID_OK:
  318. filename = dlg.GetPath()
  319. dlg.Destroy()
  320. if not filename:
  321. return
  322. # load instructions
  323. readObjectId = []
  324. readInstruction = Instruction(parent = self, objectsToDraw = readObjectId)
  325. ok = readInstruction.Read(filename)
  326. if not ok:
  327. GMessage(_("Failed to read file %s.") % filename)
  328. else:
  329. self.instruction = self.canvas.instruction = readInstruction
  330. self.objectId = self.canvas.objectId = readObjectId
  331. self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType('page').id
  332. self.canvas.UpdateMapLabel()
  333. self.canvas.dragId = -1
  334. self.canvas.Clear()
  335. self.canvas.SetPage()
  336. #self.canvas.ZoomAll()
  337. self.DialogDataChanged(self.objectId)
  338. def OnPageSetup(self, event = None):
  339. """!Specify paper size, margins and orientation"""
  340. id = self.instruction.FindInstructionByType('page').id
  341. dlg = PageSetupDialog(self, id = id, settings = self.instruction)
  342. dlg.CenterOnScreen()
  343. val = dlg.ShowModal()
  344. if val == wx.ID_OK:
  345. self.canvas.SetPage()
  346. self.getInitMap()
  347. self.canvas.RecalculatePosition(ids = self.objectId)
  348. dlg.Destroy()
  349. def OnPointer(self, event):
  350. self.toolbar.OnTool(event)
  351. self.mouse["use"] = "pointer"
  352. self.canvas.SetCursor(self.cursors["default"])
  353. self.previewCanvas.SetCursor(self.cursors["default"])
  354. def OnPan(self, event):
  355. self.toolbar.OnTool(event)
  356. self.mouse["use"] = "pan"
  357. self.canvas.SetCursor(self.cursors["hand"])
  358. self.previewCanvas.SetCursor(self.cursors["hand"])
  359. def OnZoomIn(self, event):
  360. self.toolbar.OnTool(event)
  361. self.mouse["use"] = "zoomin"
  362. self.canvas.SetCursor(self.cursors["cross"])
  363. self.previewCanvas.SetCursor(self.cursors["cross"])
  364. def OnZoomOut(self, event):
  365. self.toolbar.OnTool(event)
  366. self.mouse["use"] = "zoomout"
  367. self.canvas.SetCursor(self.cursors["cross"])
  368. self.previewCanvas.SetCursor(self.cursors["cross"])
  369. def OnZoomAll(self, event):
  370. self.mouseOld = self.mouse['use']
  371. if self.currentPage == 0:
  372. self.cursorOld = self.canvas.GetCursor()
  373. else:
  374. self.cursorOld = self.previewCanvas.GetCursor()
  375. self.previewCanvas.GetCursor()
  376. self.mouse["use"] = "zoomin"
  377. if self.currentPage == 0:
  378. self.canvas.ZoomAll()
  379. else:
  380. self.previewCanvas.ZoomAll()
  381. self.mouse["use"] = self.mouseOld
  382. if self.currentPage == 0:
  383. self.canvas.SetCursor(self.cursorOld)
  384. else:
  385. self.previewCanvas.SetCursor(self.cursorOld)
  386. def OnAddMap(self, event, notebook = False):
  387. """!Add or edit map frame"""
  388. if event is not None:
  389. if event.GetId() != self.toolbar.action['id']:
  390. self.actionOld = self.toolbar.action['id']
  391. self.mouseOld = self.mouse['use']
  392. self.cursorOld = self.canvas.GetCursor()
  393. self.toolbar.OnTool(event)
  394. if self.instruction.FindInstructionByType('map'):
  395. mapId = self.instruction.FindInstructionByType('map').id
  396. else: mapId = None
  397. id = [mapId, None, None]
  398. if notebook:
  399. if self.instruction.FindInstructionByType('vector'):
  400. vectorId = self.instruction.FindInstructionByType('vector').id
  401. else: vectorId = None
  402. if self.instruction.FindInstructionByType('raster'):
  403. rasterId = self.instruction.FindInstructionByType('raster').id
  404. else: rasterId = None
  405. id[1] = rasterId
  406. id[2] = vectorId
  407. if mapId: # map exists
  408. self.toolbar.ToggleTool(self.actionOld, True)
  409. self.toolbar.ToggleTool(self.toolbar.action['id'], False)
  410. self.toolbar.action['id'] = self.actionOld
  411. try:
  412. self.canvas.SetCursor(self.cursorOld)
  413. except AttributeError:
  414. pass
  415. ## dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  416. ## notebook = notebook)
  417. ## dlg.ShowModal()
  418. if notebook:
  419. #check map, raster, vector and save, destroy them
  420. if 'map' in self.openDialogs:
  421. self.openDialogs['map'].OnOK(event = None)
  422. if 'raster' in self.openDialogs:
  423. self.openDialogs['raster'].OnOK(event = None)
  424. if 'vector' in self.openDialogs:
  425. self.openDialogs['vector'].OnOK(event = None)
  426. if 'mapNotebook' not in self.openDialogs:
  427. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  428. notebook = notebook)
  429. self.openDialogs['mapNotebook'] = dlg
  430. self.openDialogs['mapNotebook'].Show()
  431. else:
  432. if 'mapNotebook' in self.openDialogs:
  433. self.openDialogs['mapNotebook'].notebook.ChangeSelection(0)
  434. else:
  435. if 'map' not in self.openDialogs:
  436. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  437. notebook = notebook)
  438. self.openDialogs['map'] = dlg
  439. self.openDialogs['map'].Show()
  440. else: # sofar no map
  441. self.mouse["use"] = "addMap"
  442. self.canvas.SetCursor(self.cursors["cross"])
  443. if self.currentPage == 1:
  444. self.book.SetSelection(0)
  445. self.currentPage = 0
  446. def OnAddRaster(self, event):
  447. """!Add raster map"""
  448. if self.instruction.FindInstructionByType('raster'):
  449. id = self.instruction.FindInstructionByType('raster').id
  450. else: id = None
  451. if self.instruction.FindInstructionByType('map'):
  452. mapId = self.instruction.FindInstructionByType('map').id
  453. else: mapId = None
  454. if not id:
  455. if not mapId:
  456. GMessage(message = _("Please, create map frame first."))
  457. return
  458. ## dlg = RasterDialog(self, id = id, settings = self.instruction)
  459. ## dlg.ShowModal()
  460. if 'mapNotebook' in self.openDialogs:
  461. self.openDialogs['mapNotebook'].notebook.ChangeSelection(1)
  462. else:
  463. if 'raster' not in self.openDialogs:
  464. dlg = RasterDialog(self, id = id, settings = self.instruction)
  465. self.openDialogs['raster'] = dlg
  466. self.openDialogs['raster'].Show()
  467. def OnAddVect(self, event):
  468. """!Add vector map"""
  469. if self.instruction.FindInstructionByType('vector'):
  470. id = self.instruction.FindInstructionByType('vector').id
  471. else: id = None
  472. if self.instruction.FindInstructionByType('map'):
  473. mapId = self.instruction.FindInstructionByType('map').id
  474. else: mapId = None
  475. if not id:
  476. if not mapId:
  477. GMessage(message = _("Please, create map frame first."))
  478. return
  479. ## dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  480. ## dlg.ShowModal()
  481. if 'mapNotebook' in self.openDialogs:
  482. self.openDialogs['mapNotebook'].notebook.ChangeSelection(2)
  483. else:
  484. if 'vector' not in self.openDialogs:
  485. dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  486. self.openDialogs['vector'] = dlg
  487. self.openDialogs['vector'].Show()
  488. def OnAddScalebar(self, event):
  489. """!Add scalebar"""
  490. if projInfo()['proj'] == 'll':
  491. GMessage(message = _("Scalebar is not appropriate for this projection"))
  492. return
  493. if self.instruction.FindInstructionByType('scalebar'):
  494. id = self.instruction.FindInstructionByType('scalebar').id
  495. else: id = None
  496. if 'scalebar' not in self.openDialogs:
  497. dlg = ScalebarDialog(self, id = id, settings = self.instruction)
  498. self.openDialogs['scalebar'] = dlg
  499. self.openDialogs['scalebar'].Show()
  500. def OnAddLegend(self, event, page = 0):
  501. """!Add raster or vector legend"""
  502. if self.instruction.FindInstructionByType('rasterLegend'):
  503. idR = self.instruction.FindInstructionByType('rasterLegend').id
  504. else: idR = None
  505. if self.instruction.FindInstructionByType('vectorLegend'):
  506. idV = self.instruction.FindInstructionByType('vectorLegend').id
  507. else: idV = None
  508. if 'rasterLegend' not in self.openDialogs:
  509. dlg = LegendDialog(self, id = [idR, idV], settings = self.instruction, page = page)
  510. self.openDialogs['rasterLegend'] = dlg
  511. self.openDialogs['vectorLegend'] = dlg
  512. self.openDialogs['rasterLegend'].notebook.ChangeSelection(page)
  513. self.openDialogs['rasterLegend'].Show()
  514. def OnAddMapinfo(self, event):
  515. if self.instruction.FindInstructionByType('mapinfo'):
  516. id = self.instruction.FindInstructionByType('mapinfo').id
  517. else: id = None
  518. if 'mapinfo' not in self.openDialogs:
  519. dlg = MapinfoDialog(self, id = id, settings = self.instruction)
  520. self.openDialogs['mapinfo'] = dlg
  521. self.openDialogs['mapinfo'].Show()
  522. def OnAddImage(self, event, id = None):
  523. """!Show dialog for image adding and editing"""
  524. position = None
  525. if 'image' in self.openDialogs:
  526. position = self.openDialogs['image'].GetPosition()
  527. self.openDialogs['image'].OnApply(event = None)
  528. self.openDialogs['image'].Destroy()
  529. dlg = ImageDialog(self, id = id, settings = self.instruction)
  530. self.openDialogs['image'] = dlg
  531. if position:
  532. dlg.SetPosition(position)
  533. dlg.Show()
  534. def OnAddNorthArrow(self, event, id = None):
  535. """!Show dialog for north arrow adding and editing"""
  536. if self.instruction.FindInstructionByType('northArrow'):
  537. id = self.instruction.FindInstructionByType('northArrow').id
  538. else: id = None
  539. if 'northArrow' not in self.openDialogs:
  540. dlg = NorthArrowDialog(self, id = id, settings = self.instruction)
  541. self.openDialogs['northArrow'] = dlg
  542. self.openDialogs['northArrow'].Show()
  543. def OnAddText(self, event, id = None):
  544. """!Show dialog for text adding and editing"""
  545. position = None
  546. if 'text' in self.openDialogs:
  547. position = self.openDialogs['text'].GetPosition()
  548. self.openDialogs['text'].OnApply(event = None)
  549. self.openDialogs['text'].Destroy()
  550. dlg = TextDialog(self, id = id, settings = self.instruction)
  551. self.openDialogs['text'] = dlg
  552. if position:
  553. dlg.SetPosition(position)
  554. dlg.Show()
  555. def getModifiedTextBounds(self, x, y, textExtent, rotation):
  556. """!computes bounding box of rotated text, not very precisely"""
  557. w, h = textExtent
  558. rotation = float(rotation)/180*pi
  559. H = float(w) * sin(rotation)
  560. W = float(w) * cos(rotation)
  561. X, Y = x, y
  562. if pi/2 < rotation <= 3*pi/2:
  563. X = x + W
  564. if 0 < rotation < pi:
  565. Y = y - H
  566. if rotation == 0:
  567. return wx.Rect(x,y, *textExtent)
  568. else:
  569. return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h,h)
  570. def makePSFont(self, textDict):
  571. """!creates a wx.Font object from selected postscript font. To be
  572. used for estimating bounding rectangle of text"""
  573. fontsize = textDict['fontsize'] * self.canvas.currScale
  574. fontface = textDict['font'].split('-')[0]
  575. try:
  576. fontstyle = textDict['font'].split('-')[1]
  577. except IndexError:
  578. fontstyle = ''
  579. if fontface == "Times":
  580. family = wx.FONTFAMILY_ROMAN
  581. face = "times"
  582. elif fontface == "Helvetica":
  583. family = wx.FONTFAMILY_SWISS
  584. face = 'helvetica'
  585. elif fontface == "Courier":
  586. family = wx.FONTFAMILY_TELETYPE
  587. face = 'courier'
  588. else:
  589. family = wx.FONTFAMILY_DEFAULT
  590. face = ''
  591. style = wx.FONTSTYLE_NORMAL
  592. weight = wx.FONTWEIGHT_NORMAL
  593. if 'Oblique' in fontstyle:
  594. style = wx.FONTSTYLE_SLANT
  595. if 'Italic' in fontstyle:
  596. style = wx.FONTSTYLE_ITALIC
  597. if 'Bold' in fontstyle:
  598. weight = wx.FONTWEIGHT_BOLD
  599. try:
  600. fn = wx.Font(pointSize = fontsize, family = family, style = style,
  601. weight = weight, face = face)
  602. except:
  603. fn = wx.Font(pointSize = fontsize, family = wx.FONTFAMILY_DEFAULT,
  604. style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL)
  605. return fn
  606. def getTextExtent(self, textDict):
  607. """!Estimates bounding rectangle of text"""
  608. #fontsize = str(fontsize if fontsize >= 4 else 4)
  609. dc = wx.PaintDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  610. fn = self.makePSFont(textDict)
  611. try:
  612. dc.SetFont(fn)
  613. w,h,lh = dc.GetMultiLineTextExtent(textDict['text'])
  614. return (w,h)
  615. except:
  616. return (0,0)
  617. def getInitMap(self):
  618. """!Create default map frame when no map is selected, needed for coordinates in map units"""
  619. instrFile = grass.tempfile()
  620. instrFileFd = open(instrFile, mode = 'w')
  621. instrFileFd.write(self.InstructionFile())
  622. instrFileFd.flush()
  623. instrFileFd.close()
  624. page = self.instruction.FindInstructionByType('page')
  625. mapInitRect = GetMapBounds(instrFile, portrait = (page['Orientation'] == 'Portrait'))
  626. grass.try_remove(instrFile)
  627. region = grass.region()
  628. units = UnitConversion(self)
  629. realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
  630. scale = mapInitRect.Get()[2]/realWidth
  631. initMap = self.instruction.FindInstructionByType('initMap')
  632. if initMap:
  633. id = initMap.id
  634. else:
  635. id = None
  636. if not id:
  637. id = wx.NewId()
  638. initMap = InitMap(id)
  639. self.instruction.AddInstruction(initMap)
  640. self.instruction[id].SetInstruction(dict(rect = mapInitRect, scale = scale))
  641. def OnDelete(self, event):
  642. if self.canvas.dragId != -1 and self.currentPage == 0:
  643. if self.instruction[self.canvas.dragId].type == 'map':
  644. self.deleteObject(self.canvas.dragId)
  645. self.getInitMap()
  646. self.canvas.RecalculateEN()
  647. else:
  648. self.deleteObject(self.canvas.dragId)
  649. def deleteObject(self, id):
  650. """!Deletes object, his id and redraws"""
  651. #delete from canvas
  652. self.canvas.pdcObj.RemoveId(id)
  653. if id == self.canvas.dragId:
  654. self.canvas.pdcTmp.RemoveAll()
  655. self.canvas.dragId = -1
  656. self.canvas.Refresh()
  657. # delete from instructions
  658. del self.instruction[id]
  659. def DialogDataChanged(self, id):
  660. ids = id
  661. if type(id) == int:
  662. ids = [id]
  663. for id in ids:
  664. itype = self.instruction[id].type
  665. if itype in ('scalebar', 'mapinfo', 'image'):
  666. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  667. self.canvas.UpdateLabel(itype = itype, id = id)
  668. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  669. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  670. self.canvas.RedrawSelectBox(id)
  671. if itype == 'northArrow':
  672. self.canvas.UpdateLabel(itype = itype, id = id)
  673. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  674. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  675. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'bitmap', bb = drawRectangle)
  676. self.canvas.RedrawSelectBox(id)
  677. if itype == 'text':
  678. if self.instruction[id]['rotate']:
  679. rot = float(self.instruction[id]['rotate'])
  680. else:
  681. rot = 0
  682. extent = self.getTextExtent(textDict = self.instruction[id].GetInstruction())
  683. rect = wx.Rect2D(self.instruction[id]['where'][0], self.instruction[id]['where'][1], 0, 0)
  684. self.instruction[id]['coords'] = list(self.canvas.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)[:2])
  685. #computes text coordinates according to reference point, not precisely
  686. if self.instruction[id]['ref'].split()[0] == 'lower':
  687. self.instruction[id]['coords'][1] -= extent[1]
  688. elif self.instruction[id]['ref'].split()[0] == 'center':
  689. self.instruction[id]['coords'][1] -= extent[1]/2
  690. if self.instruction[id]['ref'].split()[1] == 'right':
  691. self.instruction[id]['coords'][0] -= extent[0] * cos(rot/180*pi)
  692. self.instruction[id]['coords'][1] += extent[0] * sin(rot/180*pi)
  693. elif self.instruction[id]['ref'].split()[1] == 'center':
  694. self.instruction[id]['coords'][0] -= extent[0]/2 * cos(rot/180*pi)
  695. self.instruction[id]['coords'][1] += extent[0]/2 * sin(rot/180*pi)
  696. self.instruction[id]['coords'][0] += self.instruction[id]['xoffset']
  697. self.instruction[id]['coords'][1] -= self.instruction[id]['yoffset']
  698. coords = self.instruction[id]['coords']
  699. self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  700. self.canvas.DrawRotText(pdc = self.canvas.pdcObj, drawId = id,
  701. textDict = self.instruction[id].GetInstruction(),
  702. coords = coords, bounds = bounds)
  703. self.canvas.RedrawSelectBox(id)
  704. if itype in ('map', 'vector', 'raster'):
  705. if itype == 'raster':#set resolution
  706. info = grass.raster_info(self.instruction[id]['raster'])
  707. RunCommand('g.region', nsres = info['nsres'], ewres = info['ewres'])
  708. # change current raster in raster legend
  709. if 'rasterLegend' in self.openDialogs:
  710. self.openDialogs['rasterLegend'].updateDialog()
  711. id = self.instruction.FindInstructionByType('map').id
  712. #check resolution
  713. if itype == 'raster':
  714. SetResolution(dpi = self.instruction[id]['resolution'],
  715. width = self.instruction[id]['rect'].width,
  716. height = self.instruction[id]['rect'].height)
  717. rectCanvas = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'],
  718. canvasToPaper = False)
  719. self.canvas.RecalculateEN()
  720. self.canvas.UpdateMapLabel()
  721. self.canvas.Draw(pen = self.pen['map'], brush = self.brush['map'],
  722. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = rectCanvas)
  723. # redraw select box
  724. self.canvas.RedrawSelectBox(id)
  725. self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
  726. # redraw to get map to the bottom layer
  727. #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
  728. if itype == 'rasterLegend':
  729. if self.instruction[id]['rLegend']:
  730. self.canvas.UpdateLabel(itype = itype, id = id)
  731. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  732. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  733. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  734. self.canvas.RedrawSelectBox(id)
  735. else:
  736. self.deleteObject(id)
  737. if itype == 'vectorLegend':
  738. if not self.instruction.FindInstructionByType('vector'):
  739. self.deleteObject(id)
  740. elif self.instruction[id]['vLegend']:
  741. self.canvas.UpdateLabel(itype = itype, id = id)
  742. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  743. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  744. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  745. self.canvas.RedrawSelectBox(id)
  746. else:
  747. self.deleteObject(id)
  748. def OnPageChanged(self, event):
  749. """!Flatnotebook page has changed"""
  750. self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
  751. def OnPageChanging(self, event):
  752. """!Flatnotebook page is changing"""
  753. if self.currentPage == 0 and self.mouse['use'] == 'addMap':
  754. event.Veto()
  755. def OnHelp(self, event):
  756. """!Show help"""
  757. if self.parent and self.parent.GetName() == 'LayerManager':
  758. log = self.parent.GetLogWindow()
  759. log.RunCmd(['g.manual',
  760. 'entry=wxGUI.PsMap'])
  761. else:
  762. RunCommand('g.manual',
  763. quiet = True,
  764. entry = 'wxGUI.PsMap')
  765. def OnAbout(self, event):
  766. """!Display About window"""
  767. info = wx.AboutDialogInfo()
  768. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  769. info.SetName(_('wxGUI Cartographic Composer'))
  770. info.SetWebSite('http://grass.osgeo.org')
  771. info.SetDescription(_('(C) 2011 by the GRASS Development Team\n\n') +
  772. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  773. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 75)))
  774. wx.AboutBox(info)
  775. def OnCloseWindow(self, event):
  776. """!Close window"""
  777. try:
  778. os.remove(self.imgName)
  779. except OSError:
  780. pass
  781. grass.set_raise_on_error(False)
  782. self.Destroy()
  783. class PsMapBufferedWindow(wx.Window):
  784. """!A buffered window class.
  785. @param parent parent window
  786. @param kwargs other wx.Window parameters
  787. """
  788. def __init__(self, parent, id = wx.ID_ANY,
  789. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  790. **kwargs):
  791. wx.Window.__init__(self, parent, id = id, style = style)
  792. self.parent = parent
  793. self.FitInside()
  794. # store an off screen empty bitmap for saving to file
  795. self._buffer = None
  796. # indicates whether or not a resize event has taken place
  797. self.resize = False
  798. self.mouse = kwargs['mouse']
  799. self.cursors = kwargs['cursors']
  800. self.preview = kwargs['preview']
  801. self.pen = kwargs['pen']
  802. self.brush = kwargs['brush']
  803. if kwargs.has_key('instruction'):
  804. self.instruction = kwargs['instruction']
  805. if kwargs.has_key('openDialogs'):
  806. self.openDialogs = kwargs['openDialogs']
  807. if kwargs.has_key('pageId'):
  808. self.pageId = kwargs['pageId']
  809. if kwargs.has_key('objectId'):
  810. self.objectId = kwargs['objectId']
  811. #labels
  812. self.itemLabelsDict = { 'map': 'MAP FRAME',
  813. 'rasterLegend': 'RASTER LEGEND',
  814. 'vectorLegend': 'VECTOR LEGEND',
  815. 'mapinfo': 'MAP INFO',
  816. 'scalebar': 'SCALE BAR',
  817. 'image': 'IMAGE',
  818. 'northArrow': 'NORTH ARROW'}
  819. self.itemLabels = {}
  820. # define PseudoDC
  821. self.pdc = wx.PseudoDC()
  822. self.pdcObj = wx.PseudoDC()
  823. self.pdcPaper = wx.PseudoDC()
  824. self.pdcTmp = wx.PseudoDC()
  825. self.pdcImage = wx.PseudoDC()
  826. dc = wx.PaintDC(self)
  827. self.font = dc.GetFont()
  828. self.SetClientSize((700,510))#?
  829. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  830. self.idBoxTmp = wx.NewId()
  831. self.idZoomBoxTmp = wx.NewId()
  832. self.idResizeBoxTmp = wx.NewId()
  833. self.dragId = -1
  834. if self.preview:
  835. self.image = None
  836. self.imageId = 2000
  837. self.imgName = self.parent.imgName
  838. self.currScale = None
  839. self.Clear()
  840. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  841. self.Bind(wx.EVT_PAINT, self.OnPaint)
  842. self.Bind(wx.EVT_SIZE, self.OnSize)
  843. self.Bind(wx.EVT_IDLE, self.OnIdle)
  844. self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
  845. def Clear(self):
  846. """!Clear canvas and set paper
  847. """
  848. bg = wx.LIGHT_GREY_BRUSH
  849. self.pdcPaper.BeginDrawing()
  850. self.pdcPaper.SetBackground(bg)
  851. self.pdcPaper.Clear()
  852. self.pdcPaper.EndDrawing()
  853. self.pdcObj.RemoveAll()
  854. self.pdcTmp.RemoveAll()
  855. if not self.preview:
  856. self.SetPage()
  857. def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
  858. """!Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
  859. units = UnitConversion(self)
  860. fromU = 'pixel'
  861. toU = 'inch'
  862. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  863. pRectx, pRecty = pRect.x, pRect.y
  864. scale = 1/self.currScale
  865. if not canvasToPaper: # paper -> canvas
  866. fromU = 'inch'
  867. toU = 'pixel'
  868. scale = self.currScale
  869. pRectx = units.convert(value = - pRect.x, fromUnit = 'pixel', toUnit = 'inch' ) /scale #inch, real, negative
  870. pRecty = units.convert(value = - pRect.y, fromUnit = 'pixel', toUnit = 'inch' ) /scale
  871. Width = units.convert(value = rect.width, fromUnit = fromU, toUnit = toU) * scale
  872. Height = units.convert(value = rect.height, fromUnit = fromU, toUnit = toU) * scale
  873. X = units.convert(value = (rect.x - pRectx), fromUnit = fromU, toUnit = toU) * scale
  874. Y = units.convert(value = (rect.y - pRecty), fromUnit = fromU, toUnit = toU) * scale
  875. return wx.Rect2D(X, Y, Width, Height)
  876. def SetPage(self):
  877. """!Sets and changes page, redraws paper"""
  878. page = self.instruction[self.pageId]
  879. if not page:
  880. page = PageSetup(id = self.pageId)
  881. self.instruction.AddInstruction(page)
  882. ppi = wx.PaintDC(self).GetPPI()
  883. cW, cH = self.GetClientSize()
  884. pW, pH = page['Width']*ppi[0], page['Height']*ppi[1]
  885. if self.currScale is None:
  886. self.currScale = min(cW/pW, cH/pH)
  887. pW = pW * self.currScale
  888. pH = pH * self.currScale
  889. x = cW/2 - pW/2
  890. y = cH/2 - pH/2
  891. self.DrawPaper(wx.Rect(x, y, pW, pH))
  892. def modifyRectangle(self, r):
  893. """! Recalculates rectangle not to have negative size"""
  894. if r.GetWidth() < 0:
  895. r.SetX(r.GetX() + r.GetWidth())
  896. if r.GetHeight() < 0:
  897. r.SetY(r.GetY() + r.GetHeight())
  898. r.SetWidth(abs(r.GetWidth()))
  899. r.SetHeight(abs(r.GetHeight()))
  900. return r
  901. def RecalculateEN(self):
  902. """!Recalculate east and north for texts (eps, points) after their or map's movement"""
  903. try:
  904. mapId = self.instruction.FindInstructionByType('map').id
  905. except AttributeError:
  906. mapId = self.instruction.FindInstructionByType('initMap').id
  907. for itemType in ('text', 'image', 'northArrow'):
  908. items = self.instruction.FindInstructionByType(itemType, list = True)
  909. for item in items:
  910. e, n = PaperMapCoordinates(map = self.instruction[mapId], x = self.instruction[item.id]['where'][0],
  911. y = self.instruction[item.id]['where'][1], paperToMap = True)
  912. self.instruction[item.id]['east'], self.instruction[item.id]['north'] = e, n
  913. def OnPaint(self, event):
  914. """!Draw pseudo DC to buffer
  915. """
  916. if not self._buffer:
  917. return
  918. dc = wx.BufferedPaintDC(self, self._buffer)
  919. # use PrepareDC to set position correctly
  920. self.PrepareDC(dc)
  921. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  922. dc.Clear()
  923. # draw paper
  924. if not self.preview:
  925. self.pdcPaper.DrawToDC(dc)
  926. # draw to the DC using the calculated clipping rect
  927. rgn = self.GetUpdateRegion()
  928. if not self.preview:
  929. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  930. else:
  931. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  932. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  933. def OnMouse(self, event):
  934. if event.GetWheelRotation():
  935. zoom = event.GetWheelRotation()
  936. use = self.mouse['use']
  937. self.mouse['begin'] = event.GetPosition()
  938. if zoom > 0:
  939. self.mouse['use'] = 'zoomin'
  940. else:
  941. self.mouse['use'] = 'zoomout'
  942. zoomFactor, view = self.ComputeZoom(wx.Rect(0,0,0,0))
  943. self.Zoom(zoomFactor, view)
  944. self.mouse['use'] = use
  945. if event.Moving():
  946. if self.mouse['use'] in ('pointer', 'resize'):
  947. pos = event.GetPosition()
  948. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  949. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  950. self.SetCursor(self.cursors["sizenwse"])
  951. self.parent.SetStatusText(_('Click and drag to resize object'), 0)
  952. else:
  953. self.parent.SetStatusText('', 0)
  954. self.SetCursor(self.cursors["default"])
  955. elif event.LeftDown():
  956. self.mouse['begin'] = event.GetPosition()
  957. self.begin = self.mouse['begin']
  958. if self.mouse['use'] in ('pan', 'zoomin', 'zoomout', 'addMap'):
  959. pass
  960. #select
  961. if self.mouse['use'] == 'pointer':
  962. found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  963. foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  964. if foundResize and foundResize[0] == self.idResizeBoxTmp:
  965. self.mouse['use'] = 'resize'
  966. # when resizing, proportions match region
  967. if self.instruction[self.dragId].type == 'map':
  968. self.constraint = False
  969. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  970. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  971. self.constraint = True
  972. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  973. elif found:
  974. self.dragId = found[0]
  975. self.RedrawSelectBox(self.dragId)
  976. if self.instruction[self.dragId].type != 'map':
  977. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  978. self.Refresh()
  979. else:
  980. self.dragId = -1
  981. self.pdcTmp.RemoveId(self.idBoxTmp)
  982. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  983. self.Refresh()
  984. elif event.Dragging() and event.LeftIsDown():
  985. #draw box when zooming, creating map
  986. if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap'):
  987. self.mouse['end'] = event.GetPosition()
  988. r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
  989. self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
  990. r = self.modifyRectangle(r)
  991. self.Draw(pen = self.pen['box'], brush = self.brush['box'], pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  992. pdctype = 'rect', bb = r)
  993. # panning
  994. if self.mouse["use"] == 'pan':
  995. self.mouse['end'] = event.GetPosition()
  996. view = self.mouse['begin'][0] - self.mouse['end'][0], self.mouse['begin'][1] - self.mouse['end'][1]
  997. zoomFactor = 1
  998. self.Zoom(zoomFactor, view)
  999. self.mouse['begin'] = event.GetPosition()
  1000. #move object
  1001. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1002. self.mouse['end'] = event.GetPosition()
  1003. dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1004. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1005. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1006. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1007. if self.instruction[self.dragId].type == 'text':
  1008. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
  1009. self.instruction[self.dragId]['coords'][1] + dy
  1010. self.begin = event.GetPosition()
  1011. self.Refresh()
  1012. # resize object
  1013. if self.mouse['use'] == 'resize':
  1014. type = self.instruction[self.dragId].type
  1015. pos = event.GetPosition()
  1016. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1017. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1018. diffX = pos[0] - self.mouse['begin'][0]
  1019. diffY = pos[1] - self.mouse['begin'][1]
  1020. # match given region
  1021. if self.constraint:
  1022. if width > height:
  1023. newWidth = width + diffX
  1024. newHeight = height + diffX * (float(height) / width)
  1025. else:
  1026. newWidth = width + diffY * (float(width) / height)
  1027. newHeight = height + diffY
  1028. else:
  1029. newWidth = width + diffX
  1030. newHeight = height + diffY
  1031. if newWidth < 10 or newHeight < 10:
  1032. return
  1033. bounds = wx.Rect(x, y, newWidth, newHeight)
  1034. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj, drawid = self.dragId,
  1035. pdctype = 'rectText', bb = bounds)
  1036. self.RedrawSelectBox(self.dragId)
  1037. elif event.LeftUp():
  1038. # zoom in, zoom out
  1039. if self.mouse['use'] in ('zoomin','zoomout'):
  1040. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1041. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1042. self.Refresh()
  1043. zoomFactor, view = self.ComputeZoom(zoomR)
  1044. self.Zoom(zoomFactor, view)
  1045. # draw map frame
  1046. if self.mouse['use'] == 'addMap':
  1047. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1048. # too small rectangle, it's usually some mistake
  1049. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1050. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1051. self.Refresh()
  1052. return
  1053. rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
  1054. dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction,
  1055. rect = rectPaper)
  1056. self.openDialogs['map'] = dlg
  1057. self.openDialogs['map'].Show()
  1058. self.mouse['use'] = self.parent.mouseOld
  1059. self.SetCursor(self.parent.cursorOld)
  1060. self.parent.toolbar.ToggleTool(self.parent.actionOld, True)
  1061. self.parent.toolbar.ToggleTool(self.parent.toolbar.action['id'], False)
  1062. self.parent.toolbar.action['id'] = self.parent.actionOld
  1063. # resize resizable objects (only map sofar)
  1064. if self.mouse['use'] == 'resize':
  1065. mapId = self.instruction.FindInstructionByType('map').id
  1066. if self.dragId == mapId:
  1067. # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
  1068. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1069. newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
  1070. self.instruction[mapId]['rect'] = newRectPaper
  1071. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1072. if self.instruction[mapId]['scaleType'] == 0:
  1073. scale, foo, rect = AutoAdjust(self, scaleType = 0,
  1074. map = self.instruction[mapId]['map'],
  1075. mapType = self.instruction[mapId]['mapType'],
  1076. rect = self.instruction[mapId]['rect'])
  1077. elif self.instruction[mapId]['scaleType'] == 1:
  1078. scale, foo, rect = AutoAdjust(self, scaleType = 1,
  1079. region = self.instruction[mapId]['region'],
  1080. rect = self.instruction[mapId]['rect'])
  1081. else:
  1082. scale, foo, rect = AutoAdjust(self, scaleType = 2,
  1083. rect = self.instruction[mapId]['rect'])
  1084. self.instruction[mapId]['rect'] = rect
  1085. self.instruction[mapId]['scale'] = scale
  1086. rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
  1087. self.Draw(pen = self.pen['map'], brush = self.brush['map'],
  1088. pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
  1089. elif self.instruction[mapId]['scaleType'] == 3:
  1090. ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
  1091. #check resolution
  1092. SetResolution(dpi = self.instruction[mapId]['resolution'],
  1093. width = self.instruction[mapId]['rect'].width,
  1094. height = self.instruction[mapId]['rect'].height)
  1095. self.RedrawSelectBox(mapId)
  1096. self.Zoom(zoomFactor = 1, view = (0, 0))
  1097. self.mouse['use'] = 'pointer'
  1098. # recalculate the position of objects after dragging
  1099. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1100. if self.mouse['begin'] != event.GetPosition(): #for double click
  1101. self.RecalculatePosition(ids = [self.dragId])
  1102. if self.instruction[self.dragId].type in self.openDialogs:
  1103. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1104. # double click launches dialogs
  1105. elif event.LeftDClick():
  1106. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1107. itemCall = { 'text':self.parent.OnAddText, 'mapinfo': self.parent.OnAddMapinfo,
  1108. 'scalebar': self.parent.OnAddScalebar, 'image': self.parent.OnAddImage,
  1109. 'northArrow' : self.parent.OnAddNorthArrow,
  1110. 'rasterLegend': self.parent.OnAddLegend, 'vectorLegend': self.parent.OnAddLegend,
  1111. 'map': self.parent.OnAddMap}
  1112. itemArg = { 'text': dict(event = None, id = self.dragId), 'mapinfo': dict(event = None),
  1113. 'scalebar': dict(event = None), 'image': dict(event = None, id = self.dragId),
  1114. 'northArrow': dict(event = None, id = self.dragId),
  1115. 'rasterLegend': dict(event = None), 'vectorLegend': dict(event = None, page = 1),
  1116. 'map': dict(event = None, notebook = True)}
  1117. type = self.instruction[self.dragId].type
  1118. itemCall[type](**itemArg[type])
  1119. def RecalculatePosition(self, ids):
  1120. for id in ids:
  1121. itype = self.instruction[id].type
  1122. if itype == 'map':
  1123. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1124. canvasToPaper = True)
  1125. self.RecalculateEN()
  1126. elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1127. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1128. canvasToPaper = True)
  1129. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1130. canvasToPaper = True)[:2]
  1131. if itype in ('image', 'northArrow'):
  1132. self.RecalculateEN()
  1133. elif itype == 'scalebar':
  1134. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1135. canvasToPaper = True)
  1136. self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
  1137. elif itype == 'text':
  1138. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1139. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1140. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1141. if self.instruction[id]['rotate'] is not None:
  1142. rot = float(self.instruction[id]['rotate'])/180*pi
  1143. else:
  1144. rot = 0
  1145. if self.instruction[id]['ref'].split()[0] == 'lower':
  1146. y += extent[1]
  1147. elif self.instruction[id]['ref'].split()[0] == 'center':
  1148. y += extent[1]/2
  1149. if self.instruction[id]['ref'].split()[1] == 'right':
  1150. x += extent[0] * cos(rot)
  1151. y -= extent[0] * sin(rot)
  1152. elif self.instruction[id]['ref'].split()[1] == 'center':
  1153. x += extent[0]/2 * cos(rot)
  1154. y -= extent[0]/2 * sin(rot)
  1155. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = wx.Rect2D(x, y, 0, 0),
  1156. canvasToPaper = True)[:2]
  1157. self.RecalculateEN()
  1158. def ComputeZoom(self, rect):
  1159. """!Computes zoom factor and scroll view"""
  1160. zoomFactor = 1
  1161. cW, cH = self.GetClientSize()
  1162. cW = float(cW)
  1163. if rect.IsEmpty(): # clicked on canvas
  1164. zoomFactor = 1.5
  1165. if self.mouse['use'] == 'zoomout':
  1166. zoomFactor = 1./zoomFactor
  1167. x,y = self.mouse['begin']
  1168. xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
  1169. yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
  1170. else: #dragging
  1171. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1172. zoomFactor = 1/max(rW/cW, rH/cH)
  1173. # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
  1174. if abs(zoomFactor - 1) > 0.01:
  1175. zoomFactor = zoomFactor
  1176. else:
  1177. zoomFactor = 1.
  1178. if self.mouse['use'] == 'zoomout':
  1179. zoomFactor = min(rW/cW, rH/cH)
  1180. if rW/rH > cW/cH:
  1181. yView = rect.GetY() - (rW*(cH/cW) - rH)/2
  1182. xView = rect.GetX()
  1183. if self.mouse['use'] == 'zoomout':
  1184. x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
  1185. xView, yView = -x, -y
  1186. else:
  1187. xView = rect.GetX() - (rH*(cW/cH) - rW)/2
  1188. yView = rect.GetY()
  1189. if self.mouse['use'] == 'zoomout':
  1190. x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
  1191. xView, yView = -x, -y
  1192. return zoomFactor, (int(xView), int(yView))
  1193. def Zoom(self, zoomFactor, view):
  1194. """! Zoom to specified region, scroll view, redraw"""
  1195. if not self.currScale:
  1196. return
  1197. self.currScale = self.currScale*zoomFactor
  1198. if self.currScale > 10 or self.currScale < 0.1:
  1199. self.currScale = self.currScale/zoomFactor
  1200. return
  1201. if not self.preview:
  1202. # redraw paper
  1203. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1204. pRect.OffsetXY(-view[0], -view[1])
  1205. pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
  1206. self.DrawPaper(pRect)
  1207. #redraw objects
  1208. for id in self.objectId:
  1209. oRect = self.CanvasPaperCoordinates(
  1210. rect = self.instruction[id]['rect'], canvasToPaper = False)
  1211. type = self.instruction[id].type
  1212. if type == 'text':
  1213. coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
  1214. self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
  1215. for i, coord in enumerate(coords)]
  1216. self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
  1217. coords = coords, bounds = oRect )
  1218. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1219. if self.instruction[id]['rotate']:
  1220. rot = float(self.instruction[id]['rotate'])
  1221. else:
  1222. rot = 0
  1223. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  1224. self.pdcObj.SetIdBounds(id, bounds)
  1225. elif type == 'northArrow':
  1226. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1227. drawid = id, pdctype = 'bitmap', bb = oRect)
  1228. else:
  1229. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1230. drawid = id, pdctype = 'rectText', bb = oRect)
  1231. #redraw tmp objects
  1232. if self.dragId != -1:
  1233. self.RedrawSelectBox(self.dragId)
  1234. #redraw preview
  1235. else: # preview mode
  1236. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1237. imageRect.OffsetXY(-view[0], -view[1])
  1238. imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
  1239. self.DrawImage(imageRect)
  1240. def ZoomAll(self):
  1241. """! Zoom to full extent"""
  1242. if not self.preview:
  1243. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1244. else:
  1245. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1246. zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
  1247. zoomFactor, view = self.ComputeZoom(zoomP)
  1248. self.Zoom(zoomFactor, view)
  1249. def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0)):
  1250. """! Draw object"""
  1251. if drawid is None:
  1252. drawid = wx.NewId()
  1253. bb = bb.Get()
  1254. pdc.BeginDrawing()
  1255. pdc.RemoveId(drawid)
  1256. pdc.SetId(drawid)
  1257. pdc.SetPen(pen)
  1258. pdc.SetBrush(brush)
  1259. if pdctype == 'bitmap':
  1260. if havePILImage:
  1261. file = self.instruction[drawid]['epsfile']
  1262. rotation = self.instruction[drawid]['rotate']
  1263. self.DrawBitmap(pdc = pdc, filePath = file, rotation = rotation, bbox = bb)
  1264. else: # draw only rectangle with label
  1265. pdctype = 'rectText'
  1266. if pdctype in ('rect', 'rectText'):
  1267. pdc.DrawRectangle(*bb)
  1268. if pdctype == 'rectText':
  1269. dc = wx.PaintDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  1270. font = self.font
  1271. size = 10
  1272. font.SetPointSize(size)
  1273. font.SetStyle(wx.ITALIC)
  1274. dc.SetFont(font)
  1275. pdc.SetFont(font)
  1276. text = '\n'.join(self.itemLabels[drawid])
  1277. w,h,lh = dc.GetMultiLineTextExtent(text)
  1278. textExtent = (w,h)
  1279. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1280. r = map(int, bb)
  1281. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1282. size -= 2
  1283. font.SetPointSize(size)
  1284. dc.SetFont(font)
  1285. pdc.SetFont(font)
  1286. textExtent = dc.GetTextExtent(text)
  1287. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1288. pdc.SetTextForeground(wx.Color(100,100,100,200))
  1289. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1290. pdc.DrawText(text = text, x = textRect.x, y = textRect.y)
  1291. pdc.SetIdBounds(drawid, bb)
  1292. pdc.EndDrawing()
  1293. self.Refresh()
  1294. return drawid
  1295. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  1296. """!Draw bitmap using PIL"""
  1297. pImg = PILImage.open(filePath)
  1298. if rotation:
  1299. # get rid of black background
  1300. pImg = pImg.convert("RGBA")
  1301. rot = pImg.rotate(rotation, expand = 1)
  1302. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  1303. pImg = PILImage.composite(rot, new, rot)
  1304. pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample = PILImage.BICUBIC)
  1305. img = PilImageToWxImage(pImg)
  1306. bitmap = img.ConvertToBitmap()
  1307. mask = wx.Mask(bitmap, wx.WHITE)
  1308. bitmap.SetMask(mask)
  1309. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask = True)
  1310. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1311. if textDict['rotate']:
  1312. rot = float(textDict['rotate'])
  1313. else:
  1314. rot = 0
  1315. fontsize = textDict['fontsize'] * self.currScale
  1316. if textDict['background'] != 'none':
  1317. background = textDict['background']
  1318. else:
  1319. background = None
  1320. pdc.RemoveId(drawId)
  1321. pdc.SetId(drawId)
  1322. pdc.BeginDrawing()
  1323. # border is not redrawn when zoom changes, why?
  1324. ## if textDict['border'] != 'none' and not rot:
  1325. ## units = UnitConversion(self)
  1326. ## borderWidth = units.convert(value = textDict['width'],
  1327. ## fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  1328. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  1329. ## pdc.DrawRectangle(*bounds)
  1330. if background:
  1331. pdc.SetTextBackground(convertRGB(background))
  1332. pdc.SetBackgroundMode(wx.SOLID)
  1333. else:
  1334. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1335. fn = self.parent.makePSFont(textDict)
  1336. pdc.SetFont(fn)
  1337. pdc.SetTextForeground(convertRGB(textDict['color']))
  1338. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  1339. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  1340. self.Refresh()
  1341. pdc.EndDrawing()
  1342. def DrawImage(self, rect):
  1343. """!Draw preview image to pseudoDC"""
  1344. self.pdcImage.ClearId(self.imageId)
  1345. self.pdcImage.SetId(self.imageId)
  1346. img = self.image
  1347. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  1348. img = img.Scale(rect.width, rect.height)
  1349. bitmap = img.ConvertToBitmap()
  1350. self.pdcImage.BeginDrawing()
  1351. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  1352. self.pdcImage.SetIdBounds(self.imageId, rect)
  1353. self.pdcImage.EndDrawing()
  1354. self.Refresh()
  1355. def DrawPaper(self, rect):
  1356. """!Draw paper and margins"""
  1357. page = self.instruction[self.pageId]
  1358. scale = page['Width'] / rect.GetWidth()
  1359. w = (page['Width'] - page['Right'] - page['Left']) / scale
  1360. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  1361. x = page['Left'] / scale + rect.GetX()
  1362. y = page['Top'] / scale + rect.GetY()
  1363. self.pdcPaper.BeginDrawing()
  1364. self.pdcPaper.RemoveId(self.pageId)
  1365. self.pdcPaper.SetId(self.pageId)
  1366. self.pdcPaper.SetPen(self.pen['paper'])
  1367. self.pdcPaper.SetBrush(self.brush['paper'])
  1368. self.pdcPaper.DrawRectangleRect(rect)
  1369. self.pdcPaper.SetPen(self.pen['margins'])
  1370. self.pdcPaper.SetBrush(self.brush['margins'])
  1371. self.pdcPaper.DrawRectangle(x, y, w, h)
  1372. self.pdcPaper.SetIdBounds(self.pageId, rect)
  1373. self.pdcPaper.EndDrawing()
  1374. self.Refresh()
  1375. def ImageRect(self):
  1376. """!Returns image centered in canvas, computes scale"""
  1377. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  1378. cW, cH = self.GetClientSize()
  1379. iW, iH = img.GetWidth(), img.GetHeight()
  1380. self.currScale = min(float(cW)/iW, float(cH)/iH)
  1381. iW = iW * self.currScale
  1382. iH = iH * self.currScale
  1383. x = cW/2 - iW/2
  1384. y = cH/2 - iH/2
  1385. imageRect = wx.Rect(x, y, iW, iH)
  1386. return imageRect
  1387. def RedrawSelectBox(self, id):
  1388. """!Redraws select box when selected object changes its size"""
  1389. if self.dragId == id:
  1390. rect = [self.pdcObj.GetIdBounds(id).Inflate(3,3)]
  1391. type = ['select']
  1392. ids = [self.idBoxTmp]
  1393. if self.instruction[id].type == 'map':
  1394. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  1395. rect.append(wx.Rect(controlP.x, controlP.y, 10,10))
  1396. type.append('resize')
  1397. ids.append(self.idResizeBoxTmp)
  1398. for id, type, rect in zip(ids, type, rect):
  1399. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcTmp,
  1400. drawid = id, pdctype = 'rect', bb = rect)
  1401. def UpdateMapLabel(self):
  1402. """!Updates map frame label"""
  1403. vector = self.instruction.FindInstructionByType('vector')
  1404. if vector:
  1405. vectorId = vector.id
  1406. else:
  1407. vectorId = None
  1408. raster = self.instruction.FindInstructionByType('raster')
  1409. if raster:
  1410. rasterId = raster.id
  1411. else:
  1412. rasterId = None
  1413. rasterName = 'None'
  1414. if rasterId:
  1415. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  1416. mapId = self.instruction.FindInstructionByType('map').id
  1417. self.itemLabels[mapId] = []
  1418. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  1419. self.itemLabels[mapId].append("raster: " + rasterName)
  1420. if vectorId:
  1421. for map in self.instruction[vectorId]['list']:
  1422. self.itemLabels[mapId].append('vector: ' + map[0].split('@')[0])
  1423. def UpdateLabel(self, itype, id):
  1424. self.itemLabels[id] = []
  1425. self.itemLabels[id].append(self.itemLabelsDict[itype])
  1426. if itype == 'image':
  1427. file = os.path.basename(self.instruction[id]['epsfile'])
  1428. self.itemLabels[id].append(file)
  1429. def OnSize(self, event):
  1430. """!Init image size to match window size
  1431. """
  1432. # not zoom all when notebook page is changed
  1433. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  1434. self.ZoomAll()
  1435. self.OnIdle(None)
  1436. event.Skip()
  1437. def OnIdle(self, event):
  1438. """!Only re-render a image during idle time instead of
  1439. multiple times during resizing.
  1440. """
  1441. width, height = self.GetClientSize()
  1442. # Make new off screen bitmap: this bitmap will always have the
  1443. # current drawing in it, so it can be used to save the image
  1444. # to a file, or whatever.
  1445. self._buffer = wx.EmptyBitmap(width, height)
  1446. # re-render image on idle
  1447. self.resize = True
  1448. def ScaleRect(self, rect, scale):
  1449. """! Scale rectangle"""
  1450. return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
  1451. rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)
  1452. def main():
  1453. import gettext
  1454. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1455. app = wx.PySimpleApp()
  1456. wx.InitAllImageHandlers()
  1457. frame = PsMapFrame()
  1458. frame.Show()
  1459. app.MainLoop()
  1460. if __name__ == "__main__":
  1461. main()