frame.py 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286
  1. """!
  2. @package psmap.frame
  3. @brief GUI for ps.map
  4. Classes:
  5. - frame::PsMapFrame
  6. - frame::PsMapBufferedWindow
  7. (C) 2011-2012 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, sqrt
  18. import wx
  19. try:
  20. import wx.lib.agw.flatnotebook as fnb
  21. except ImportError:
  22. import wx.lib.flatnotebook as fnb
  23. import grass.script as grass
  24. from core import globalvar
  25. from gui_core.menu import Menu
  26. from core.gconsole import CmdThread, EVT_CMD_DONE
  27. from psmap.toolbars import PsMapToolbar
  28. from core.gcmd import RunCommand, GError, GMessage
  29. from core.settings import UserSettings
  30. from gui_core.forms import GUI
  31. from gui_core.dialogs import HyperlinkDialog
  32. from psmap.menudata import PsMapMenuData
  33. from psmap.dialogs import *
  34. from psmap.instructions import *
  35. from psmap.utils import *
  36. class PsMapFrame(wx.Frame):
  37. def __init__(self, parent = None, id = wx.ID_ANY,
  38. title = _("GRASS GIS Cartographic Composer"), **kwargs):
  39. """!Main window of ps.map GUI
  40. @param parent parent window
  41. @param id window id
  42. @param title window title
  43. @param kwargs wx.Frames' arguments
  44. """
  45. self.parent = parent
  46. wx.Frame.__init__(self, parent = parent, id = id, title = title, name = "PsMap", **kwargs)
  47. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  48. #menubar
  49. self.menubar = Menu(parent = self, model = PsMapMenuData().GetModel())
  50. self.SetMenuBar(self.menubar)
  51. #toolbar
  52. self.toolbar = PsMapToolbar(parent = self)
  53. self.SetToolBar(self.toolbar)
  54. self.actionOld = self.toolbar.action['id']
  55. self.iconsize = (16, 16)
  56. #satusbar
  57. self.statusbar = self.CreateStatusBar(number = 1)
  58. # mouse attributes -- position on the screen, begin and end of
  59. # dragging, and type of drawing
  60. self.mouse = {
  61. 'begin': [0, 0], # screen coordinates
  62. 'end' : [0, 0],
  63. 'use' : "pointer",
  64. }
  65. # available cursors
  66. self.cursors = {
  67. "default" : wx.StockCursor(wx.CURSOR_ARROW),
  68. "cross" : wx.StockCursor(wx.CURSOR_CROSS),
  69. "hand" : wx.StockCursor(wx.CURSOR_HAND),
  70. "sizenwse": wx.StockCursor(wx.CURSOR_SIZENWSE)
  71. }
  72. # pen and brush
  73. self.pen = {
  74. 'paper': wx.Pen(colour = "BLACK", width = 1),
  75. 'margins': wx.Pen(colour = "GREY", width = 1),
  76. 'map': wx.Pen(colour = wx.Colour(86, 122, 17), width = 2),
  77. 'rasterLegend': wx.Pen(colour = wx.Colour(219, 216, 4), width = 2),
  78. 'vectorLegend': wx.Pen(colour = wx.Colour(219, 216, 4), width = 2),
  79. 'mapinfo': wx.Pen(colour = wx.Colour(5, 184, 249), width = 2),
  80. 'scalebar': wx.Pen(colour = wx.Colour(150, 150, 150), width = 2),
  81. 'image': wx.Pen(colour = wx.Colour(255, 150, 50), width = 2),
  82. 'northArrow': wx.Pen(colour = wx.Colour(200, 200, 200), width = 2),
  83. 'point': wx.Pen(colour = wx.Colour(100, 100, 100), width = 2),
  84. 'line': wx.Pen(colour = wx.Colour(0, 0, 0), width = 2),
  85. 'box': wx.Pen(colour = 'RED', width = 2, style = wx.SHORT_DASH),
  86. 'select': wx.Pen(colour = 'BLACK', width = 1, style = wx.SHORT_DASH),
  87. 'resize': wx.Pen(colour = 'BLACK', width = 1)
  88. }
  89. self.brush = {
  90. 'paper': wx.WHITE_BRUSH,
  91. 'margins': wx.TRANSPARENT_BRUSH,
  92. 'map': wx.Brush(wx.Colour(151, 214, 90)),
  93. 'rasterLegend': wx.Brush(wx.Colour(250, 247, 112)),
  94. 'vectorLegend': wx.Brush(wx.Colour(250, 247, 112)),
  95. 'mapinfo': wx.Brush(wx.Colour(127, 222, 252)),
  96. 'scalebar': wx.Brush(wx.Colour(200, 200, 200)),
  97. 'image': wx.Brush(wx.Colour(255, 200, 50)),
  98. 'northArrow': wx.Brush(wx.Colour(255, 255, 255)),
  99. 'point': wx.Brush(wx.Colour(200, 200, 200)),
  100. 'line': wx.TRANSPARENT_BRUSH,
  101. 'box': wx.TRANSPARENT_BRUSH,
  102. 'select':wx.TRANSPARENT_BRUSH,
  103. 'resize': wx.BLACK_BRUSH
  104. }
  105. # list of objects to draw
  106. self.objectId = []
  107. # instructions
  108. self.instruction = Instruction(parent = self, objectsToDraw = self.objectId)
  109. # open dialogs
  110. self.openDialogs = dict()
  111. self.pageId = wx.NewId()
  112. #current page of flatnotebook
  113. self.currentPage = 0
  114. #canvas for draft mode
  115. self.canvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, pen = self.pen,
  116. brush = self.brush, cursors = self.cursors,
  117. instruction = self.instruction, openDialogs = self.openDialogs,
  118. pageId = self.pageId, objectId = self.objectId,
  119. preview = False)
  120. self.canvas.SetCursor(self.cursors["default"])
  121. self.getInitMap()
  122. # image path
  123. env = grass.gisenv()
  124. self.imgName = grass.tempfile()
  125. #canvas for preview
  126. self.previewCanvas = PsMapBufferedWindow(parent = self, mouse = self.mouse, cursors = self.cursors,
  127. pen = self.pen, brush = self.brush, preview = True)
  128. # set WIND_OVERRIDE
  129. grass.use_temp_region()
  130. # create queues
  131. self.requestQ = Queue.Queue()
  132. self.resultQ = Queue.Queue()
  133. # thread
  134. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  135. self._layout()
  136. self.SetMinSize(wx.Size(775, 600))
  137. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
  138. self.Bind(fnb.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  139. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  140. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  141. if not havePILImage:
  142. wx.CallAfter(self._showErrMsg)
  143. def _showErrMsg(self):
  144. """!Show error message (missing preview)
  145. """
  146. GError(parent = self,
  147. message = _("Python Imaging Library is not available.\n"
  148. "'Preview' functionality won't work."),
  149. showTraceback = False)
  150. def _layout(self):
  151. """!Do layout
  152. """
  153. mainSizer = wx.BoxSizer(wx.VERTICAL)
  154. if globalvar.hasAgw:
  155. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  156. agwStyle = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  157. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  158. else:
  159. self.book = fnb.FlatNotebook(parent = self, id = wx.ID_ANY,
  160. style = fnb.FNB_FANCY_TABS | fnb.FNB_BOTTOM |
  161. fnb.FNB_NO_NAV_BUTTONS | fnb.FNB_NO_X_BUTTON)
  162. #self.book = fnb.FlatNotebook(self, wx.ID_ANY, style = fnb.FNB_BOTTOM)
  163. self.book.AddPage(self.canvas, "Draft mode")
  164. self.book.AddPage(self.previewCanvas, "Preview")
  165. self.book.SetSelection(0)
  166. mainSizer.Add(self.book,1, wx.EXPAND)
  167. self.SetSizer(mainSizer)
  168. mainSizer.Fit(self)
  169. def InstructionFile(self):
  170. """!Creates mapping instructions"""
  171. return str(self.instruction)
  172. def OnPSFile(self, event):
  173. """!Generate PostScript"""
  174. filename = self.getFile(wildcard = "PostScript (*.ps)|*.ps|Encapsulated PostScript (*.eps)|*.eps")
  175. if filename:
  176. self.PSFile(filename)
  177. def OnPsMapDialog(self, event):
  178. """!Launch ps.map dialog
  179. """
  180. GUI(parent = self).ParseCommand(cmd = ['ps.map'])
  181. def OnPDFFile(self, event):
  182. """!Generate PDF from PS with ps2pdf if available"""
  183. if not sys.platform == 'win32':
  184. try:
  185. p = grass.Popen(["ps2pdf"], stderr = grass.PIPE)
  186. p.stderr.close()
  187. except OSError:
  188. GMessage(parent = self,
  189. message = _("Program ps2pdf is not available. Please install it first to create PDF."))
  190. return
  191. filename = self.getFile(wildcard = "PDF (*.pdf)|*.pdf")
  192. if filename:
  193. self.PSFile(filename, pdf = True)
  194. def OnPreview(self, event):
  195. """!Run ps.map and show result"""
  196. self.PSFile()
  197. def PSFile(self, filename = None, pdf = False):
  198. """!Create temporary instructions file and run ps.map with output = filename"""
  199. instrFile = grass.tempfile()
  200. instrFileFd = open(instrFile, mode = 'w')
  201. instrFileFd.write(self.InstructionFile())
  202. instrFileFd.flush()
  203. instrFileFd.close()
  204. temp = False
  205. regOld = grass.region()
  206. if pdf:
  207. pdfname = filename
  208. else:
  209. pdfname = None
  210. #preview or pdf
  211. if not filename or (filename and pdf):
  212. temp = True
  213. filename = grass.tempfile()
  214. if not pdf: # lower resolution for preview
  215. if self.instruction.FindInstructionByType('map'):
  216. mapId = self.instruction.FindInstructionByType('map').id
  217. SetResolution(dpi = 100, width = self.instruction[mapId]['rect'][2],
  218. height = self.instruction[mapId]['rect'][3])
  219. cmd = ['ps.map', '--overwrite']
  220. if os.path.splitext(filename)[1] == '.eps':
  221. cmd.append('-e')
  222. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  223. cmd.append('-r')
  224. cmd.append('input=%s' % instrFile)
  225. cmd.append('output=%s' % filename)
  226. if pdf:
  227. self.SetStatusText(_('Generating PDF...'), 0)
  228. elif not temp:
  229. self.SetStatusText(_('Generating PostScript...'), 0)
  230. else:
  231. self.SetStatusText(_('Generating preview...'), 0)
  232. self.cmdThread.RunCmd(cmd, userData = {'instrFile' : instrFile, 'filename' : filename,
  233. 'pdfname' : pdfname, 'temp' : temp, 'regionOld' : regOld})
  234. def OnCmdDone(self, event):
  235. """!ps.map process finished"""
  236. if event.returncode != 0:
  237. GMessage(parent = self,
  238. message = _("Ps.map exited with return code %s") % event.returncode)
  239. grass.try_remove(event.userData['instrFile'])
  240. if event.userData['temp']:
  241. grass.try_remove(event.userData['filename'])
  242. return
  243. if event.userData['pdfname']:
  244. if sys.platform == 'win32':
  245. command = ['gswin32c',
  246. '-P-', '-dSAFER',
  247. '-dCompatibilityLevel=1.4',
  248. '-q', '-P-',
  249. '-dNOPAUSE', '-dBATCH',
  250. '-sDEVICE=pdfwrite',
  251. '-dPDFSETTINGS=/prepress', '-r1200',
  252. '-sstdout=%stderr',
  253. '-sOutputFile=%s' % event.userData['pdfname'],
  254. '-P-', '-dSAFER',
  255. '-dCompatibilityLevel=1.4',
  256. '-c', '.setpdfwrite', '-f',
  257. event.userData['filename']]
  258. else:
  259. command = ['ps2pdf', '-dPDFSETTINGS=/prepress', '-r1200',
  260. event.userData['filename'], event.userData['pdfname']]
  261. try:
  262. proc = grass.Popen(command)
  263. ret = proc.wait()
  264. if ret > 0:
  265. GMessage(parent = self,
  266. message = _("%(prg)s exited with return code %(code)s") % {'prg': command[0],
  267. 'code': ret})
  268. else:
  269. self.SetStatusText(_('PDF generated'), 0)
  270. except OSError, e:
  271. GError(parent = self,
  272. message = _("Program ps2pdf is not available. Please install it to create PDF.\n\n %s") % e)
  273. elif not event.userData['temp']:
  274. self.SetStatusText(_('PostScript file generated'), 0)
  275. # show preview only when user doesn't want to create ps or pdf
  276. if havePILImage and event.userData['temp'] and not event.userData['pdfname']:
  277. RunCommand('g.region', cols = event.userData['regionOld']['cols'], rows = event.userData['regionOld']['rows'])
  278. # wx.BusyInfo does not display the message
  279. busy = wx.BusyInfo(message = _("Generating preview, wait please"), parent = self)
  280. wx.Yield()
  281. try:
  282. im = PILImage.open(event.userData['filename'])
  283. if self.instruction[self.pageId]['Orientation'] == 'Landscape':
  284. im = im.rotate(270)
  285. # hack for Windows, change method for loading EPS
  286. if sys.platform == 'win32':
  287. import types
  288. im.load = types.MethodType(loadPSForWindows, im)
  289. im.save(self.imgName, format = 'PNG')
  290. except IOError, e:
  291. del busy
  292. dlg = HyperlinkDialog(self, title=_("Preview not available"),
  293. message=_("Preview is not available probably due to missing Ghostscript."),
  294. hyperlink='http://trac.osgeo.org/grass/wiki/CompileOnWindows#Ghostscript',
  295. hyperlinkLabel=_("Please follow instructions on GRASS Trac Wiki."))
  296. dlg.ShowModal()
  297. dlg.Destroy()
  298. return
  299. rect = self.previewCanvas.ImageRect()
  300. self.previewCanvas.image = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  301. self.previewCanvas.DrawImage(rect = rect)
  302. del busy
  303. self.SetStatusText(_('Preview generated'), 0)
  304. self.book.SetSelection(1)
  305. self.currentPage = 1
  306. grass.try_remove(event.userData['instrFile'])
  307. if event.userData['temp']:
  308. grass.try_remove(event.userData['filename'])
  309. wx.CallLater(4000, lambda: self.SetStatusText("", 0))
  310. def getFile(self, wildcard):
  311. suffix = []
  312. for filter in wildcard.split('|')[1::2]:
  313. s = filter.strip('*').split('.')[1]
  314. if s:
  315. s = '.' + s
  316. suffix.append(s)
  317. raster = self.instruction.FindInstructionByType('raster')
  318. if raster:
  319. rasterId = raster.id
  320. else:
  321. rasterId = None
  322. if rasterId and self.instruction[rasterId]['raster']:
  323. mapName = self.instruction[rasterId]['raster'].split('@')[0] + suffix[0]
  324. else:
  325. mapName = ''
  326. filename = ''
  327. dlg = wx.FileDialog(self, message = _("Save file as"), defaultDir = "",
  328. defaultFile = mapName, wildcard = wildcard,
  329. style = wx.CHANGE_DIR | wx.SAVE | wx.OVERWRITE_PROMPT)
  330. if dlg.ShowModal() == wx.ID_OK:
  331. filename = dlg.GetPath()
  332. suffix = suffix[dlg.GetFilterIndex()]
  333. if not os.path.splitext(filename)[1]:
  334. filename = filename + suffix
  335. elif os.path.splitext(filename)[1] != suffix and suffix != '':
  336. filename = os.path.splitext(filename)[0] + suffix
  337. dlg.Destroy()
  338. return filename
  339. def OnInstructionFile(self, event):
  340. filename = self.getFile(wildcard = "*.psmap|*.psmap|Text file(*.txt)|*.txt|All files(*.*)|*.*")
  341. if filename:
  342. instrFile = open(filename, "w")
  343. instrFile.write(self.InstructionFile())
  344. instrFile.close()
  345. def OnLoadFile(self, event):
  346. """!Launch file dialog and load selected file"""
  347. #find file
  348. filename = ''
  349. dlg = wx.FileDialog(self, message = "Find instructions file", defaultDir = "",
  350. defaultFile = '', wildcard = "All files (*.*)|*.*",
  351. style = wx.CHANGE_DIR|wx.OPEN)
  352. if dlg.ShowModal() == wx.ID_OK:
  353. filename = dlg.GetPath()
  354. dlg.Destroy()
  355. if not filename:
  356. return
  357. # load instructions
  358. self.LoadFile(filename)
  359. def LoadFile(self, filename):
  360. """!Load file and read instructions"""
  361. readObjectId = []
  362. readInstruction = Instruction(parent = self, objectsToDraw = readObjectId)
  363. ok = readInstruction.Read(filename)
  364. if not ok:
  365. GMessage(_("Failed to read file %s.") % filename)
  366. else:
  367. self.instruction = self.canvas.instruction = readInstruction
  368. self.objectId = self.canvas.objectId = readObjectId
  369. self.pageId = self.canvas.pageId = self.instruction.FindInstructionByType('page').id
  370. self.canvas.UpdateMapLabel()
  371. self.canvas.dragId = -1
  372. self.canvas.Clear()
  373. self.canvas.SetPage()
  374. #self.canvas.ZoomAll()
  375. self.DialogDataChanged(self.objectId)
  376. def OnPageSetup(self, event = None):
  377. """!Specify paper size, margins and orientation"""
  378. id = self.instruction.FindInstructionByType('page').id
  379. dlg = PageSetupDialog(self, id = id, settings = self.instruction)
  380. dlg.CenterOnScreen()
  381. val = dlg.ShowModal()
  382. if val == wx.ID_OK:
  383. self.canvas.SetPage()
  384. self.getInitMap()
  385. self.canvas.RecalculatePosition(ids = self.objectId)
  386. dlg.Destroy()
  387. def OnPointer(self, event):
  388. self.toolbar.OnTool(event)
  389. self.mouse["use"] = "pointer"
  390. self.canvas.SetCursor(self.cursors["default"])
  391. self.previewCanvas.SetCursor(self.cursors["default"])
  392. def OnPan(self, event):
  393. self.toolbar.OnTool(event)
  394. self.mouse["use"] = "pan"
  395. self.canvas.SetCursor(self.cursors["hand"])
  396. self.previewCanvas.SetCursor(self.cursors["hand"])
  397. def OnZoomIn(self, event):
  398. self.toolbar.OnTool(event)
  399. self.mouse["use"] = "zoomin"
  400. self.canvas.SetCursor(self.cursors["cross"])
  401. self.previewCanvas.SetCursor(self.cursors["cross"])
  402. def OnZoomOut(self, event):
  403. self.toolbar.OnTool(event)
  404. self.mouse["use"] = "zoomout"
  405. self.canvas.SetCursor(self.cursors["cross"])
  406. self.previewCanvas.SetCursor(self.cursors["cross"])
  407. def OnZoomAll(self, event):
  408. self.mouseOld = self.mouse['use']
  409. if self.currentPage == 0:
  410. self.cursorOld = self.canvas.GetCursor()
  411. else:
  412. self.cursorOld = self.previewCanvas.GetCursor()
  413. self.previewCanvas.GetCursor()
  414. self.mouse["use"] = "zoomin"
  415. if self.currentPage == 0:
  416. self.canvas.ZoomAll()
  417. else:
  418. self.previewCanvas.ZoomAll()
  419. self.mouse["use"] = self.mouseOld
  420. if self.currentPage == 0:
  421. self.canvas.SetCursor(self.cursorOld)
  422. else:
  423. self.previewCanvas.SetCursor(self.cursorOld)
  424. def OnAddMap(self, event, notebook = False):
  425. """!Add or edit map frame"""
  426. if event is not None:
  427. if event.GetId() != self.toolbar.action['id']:
  428. self.actionOld = self.toolbar.action['id']
  429. self.mouseOld = self.mouse['use']
  430. self.cursorOld = self.canvas.GetCursor()
  431. self.toolbar.OnTool(event)
  432. if self.instruction.FindInstructionByType('map'):
  433. mapId = self.instruction.FindInstructionByType('map').id
  434. else: mapId = None
  435. id = [mapId, None, None]
  436. if notebook:
  437. if self.instruction.FindInstructionByType('vector'):
  438. vectorId = self.instruction.FindInstructionByType('vector').id
  439. else: vectorId = None
  440. if self.instruction.FindInstructionByType('raster'):
  441. rasterId = self.instruction.FindInstructionByType('raster').id
  442. else: rasterId = None
  443. id[1] = rasterId
  444. id[2] = vectorId
  445. if mapId: # map exists
  446. self.toolbar.ToggleTool(self.actionOld, True)
  447. self.toolbar.ToggleTool(self.toolbar.action['id'], False)
  448. self.toolbar.action['id'] = self.actionOld
  449. try:
  450. self.canvas.SetCursor(self.cursorOld)
  451. except AttributeError:
  452. pass
  453. ## dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  454. ## notebook = notebook)
  455. ## dlg.ShowModal()
  456. if notebook:
  457. #check map, raster, vector and save, destroy them
  458. if 'map' in self.openDialogs:
  459. self.openDialogs['map'].OnOK(event = None)
  460. if 'raster' in self.openDialogs:
  461. self.openDialogs['raster'].OnOK(event = None)
  462. if 'vector' in self.openDialogs:
  463. self.openDialogs['vector'].OnOK(event = None)
  464. if 'mapNotebook' not in self.openDialogs:
  465. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  466. notebook = notebook)
  467. self.openDialogs['mapNotebook'] = dlg
  468. self.openDialogs['mapNotebook'].Show()
  469. else:
  470. if 'mapNotebook' in self.openDialogs:
  471. self.openDialogs['mapNotebook'].notebook.ChangeSelection(0)
  472. else:
  473. if 'map' not in self.openDialogs:
  474. dlg = MapDialog(parent = self, id = id, settings = self.instruction,
  475. notebook = notebook)
  476. self.openDialogs['map'] = dlg
  477. self.openDialogs['map'].Show()
  478. else: # sofar no map
  479. self.mouse["use"] = "addMap"
  480. self.canvas.SetCursor(self.cursors["cross"])
  481. if self.currentPage == 1:
  482. self.book.SetSelection(0)
  483. self.currentPage = 0
  484. def OnAddRaster(self, event):
  485. """!Add raster map"""
  486. if self.instruction.FindInstructionByType('raster'):
  487. id = self.instruction.FindInstructionByType('raster').id
  488. else: id = None
  489. if self.instruction.FindInstructionByType('map'):
  490. mapId = self.instruction.FindInstructionByType('map').id
  491. else: mapId = None
  492. if not id:
  493. if not mapId:
  494. GMessage(message = _("Please, create map frame first."))
  495. return
  496. ## dlg = RasterDialog(self, id = id, settings = self.instruction)
  497. ## dlg.ShowModal()
  498. if 'mapNotebook' in self.openDialogs:
  499. self.openDialogs['mapNotebook'].notebook.ChangeSelection(1)
  500. else:
  501. if 'raster' not in self.openDialogs:
  502. dlg = RasterDialog(self, id = id, settings = self.instruction)
  503. self.openDialogs['raster'] = dlg
  504. self.openDialogs['raster'].Show()
  505. def OnAddVect(self, event):
  506. """!Add vector map"""
  507. if self.instruction.FindInstructionByType('vector'):
  508. id = self.instruction.FindInstructionByType('vector').id
  509. else: id = None
  510. if self.instruction.FindInstructionByType('map'):
  511. mapId = self.instruction.FindInstructionByType('map').id
  512. else: mapId = None
  513. if not id:
  514. if not mapId:
  515. GMessage(message = _("Please, create map frame first."))
  516. return
  517. ## dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  518. ## dlg.ShowModal()
  519. if 'mapNotebook' in self.openDialogs:
  520. self.openDialogs['mapNotebook'].notebook.ChangeSelection(2)
  521. else:
  522. if 'vector' not in self.openDialogs:
  523. dlg = MainVectorDialog(self, id = id, settings = self.instruction)
  524. self.openDialogs['vector'] = dlg
  525. self.openDialogs['vector'].Show()
  526. def OnAddScalebar(self, event):
  527. """!Add scalebar"""
  528. if projInfo()['proj'] == 'll':
  529. GMessage(message = _("Scalebar is not appropriate for this projection"))
  530. return
  531. if self.instruction.FindInstructionByType('scalebar'):
  532. id = self.instruction.FindInstructionByType('scalebar').id
  533. else: id = None
  534. if 'scalebar' not in self.openDialogs:
  535. dlg = ScalebarDialog(self, id = id, settings = self.instruction)
  536. self.openDialogs['scalebar'] = dlg
  537. self.openDialogs['scalebar'].Show()
  538. def OnAddLegend(self, event, page = 0):
  539. """!Add raster or vector legend"""
  540. if self.instruction.FindInstructionByType('rasterLegend'):
  541. idR = self.instruction.FindInstructionByType('rasterLegend').id
  542. else: idR = None
  543. if self.instruction.FindInstructionByType('vectorLegend'):
  544. idV = self.instruction.FindInstructionByType('vectorLegend').id
  545. else: idV = None
  546. if 'rasterLegend' not in self.openDialogs:
  547. dlg = LegendDialog(self, id = [idR, idV], settings = self.instruction, page = page)
  548. self.openDialogs['rasterLegend'] = dlg
  549. self.openDialogs['vectorLegend'] = dlg
  550. self.openDialogs['rasterLegend'].notebook.ChangeSelection(page)
  551. self.openDialogs['rasterLegend'].Show()
  552. def OnAddMapinfo(self, event):
  553. if self.instruction.FindInstructionByType('mapinfo'):
  554. id = self.instruction.FindInstructionByType('mapinfo').id
  555. else: id = None
  556. if 'mapinfo' not in self.openDialogs:
  557. dlg = MapinfoDialog(self, id = id, settings = self.instruction)
  558. self.openDialogs['mapinfo'] = dlg
  559. self.openDialogs['mapinfo'].Show()
  560. def OnAddImage(self, event, id = None):
  561. """!Show dialog for image adding and editing"""
  562. position = None
  563. if 'image' in self.openDialogs:
  564. position = self.openDialogs['image'].GetPosition()
  565. self.openDialogs['image'].OnApply(event = None)
  566. self.openDialogs['image'].Destroy()
  567. dlg = ImageDialog(self, id = id, settings = self.instruction)
  568. self.openDialogs['image'] = dlg
  569. if position:
  570. dlg.SetPosition(position)
  571. dlg.Show()
  572. def OnAddNorthArrow(self, event, id = None):
  573. """!Show dialog for north arrow adding and editing"""
  574. if self.instruction.FindInstructionByType('northArrow'):
  575. id = self.instruction.FindInstructionByType('northArrow').id
  576. else: id = None
  577. if 'northArrow' not in self.openDialogs:
  578. dlg = NorthArrowDialog(self, id = id, settings = self.instruction)
  579. self.openDialogs['northArrow'] = dlg
  580. self.openDialogs['northArrow'].Show()
  581. def OnAddText(self, event, id = None):
  582. """!Show dialog for text adding and editing"""
  583. position = None
  584. if 'text' in self.openDialogs:
  585. position = self.openDialogs['text'].GetPosition()
  586. self.openDialogs['text'].OnApply(event = None)
  587. self.openDialogs['text'].Destroy()
  588. dlg = TextDialog(self, id = id, settings = self.instruction)
  589. self.openDialogs['text'] = dlg
  590. if position:
  591. dlg.SetPosition(position)
  592. dlg.Show()
  593. def OnAddPoint(self, event):
  594. """!Add point action selected"""
  595. self.mouse["use"] = "addPoint"
  596. self.canvas.SetCursor(self.cursors["cross"])
  597. def AddPoint(self, id = None, coordinates = None):
  598. """!Add point and open property dialog.
  599. @param id id point id (None if creating new point)
  600. @param coordinates coordinates of new point
  601. """
  602. position = None
  603. if 'point' in self.openDialogs:
  604. position = self.openDialogs['point'].GetPosition()
  605. self.openDialogs['point'].OnApply(event = None)
  606. self.openDialogs['point'].Destroy()
  607. dlg = PointDialog(self, id = id, settings = self.instruction,
  608. coordinates = coordinates)
  609. self.openDialogs['point'] = dlg
  610. if position:
  611. dlg.SetPosition(position)
  612. if coordinates:
  613. dlg.OnApply(event = None)
  614. dlg.Show()
  615. def OnAddLine(self, event):
  616. """!Add line action selected"""
  617. self.mouse["use"] = "addLine"
  618. self.canvas.SetCursor(self.cursors["cross"])
  619. def AddLine(self, id = None, coordinates = None):
  620. """!Add line and open property dialog.
  621. @param id id line id (None if creating new line)
  622. @param coordinates coordinates of new line
  623. """
  624. position = None
  625. if 'line' in self.openDialogs:
  626. position = self.openDialogs['line'].GetPosition()
  627. self.openDialogs['line'].OnApply(event = None)
  628. self.openDialogs['line'].Destroy()
  629. dlg = RectangleDialog(self, id = id, settings = self.instruction,
  630. type = 'line', coordinates = coordinates)
  631. self.openDialogs['line'] = dlg
  632. if position:
  633. dlg.SetPosition(position)
  634. if coordinates:
  635. dlg.OnApply(event = None)
  636. dlg.Show()
  637. def OnAddRectangle(self, event):
  638. """!Add rectangle action selected"""
  639. self.mouse["use"] = "addRectangle"
  640. self.canvas.SetCursor(self.cursors["cross"])
  641. def AddRectangle(self, id = None, coordinates = None):
  642. """!Add rectangle and open property dialog.
  643. @param id id rectangle id (None if creating new rectangle)
  644. @param coordinates coordinates of new rectangle
  645. """
  646. position = None
  647. if 'rectangle' in self.openDialogs:
  648. position = self.openDialogs['rectangle'].GetPosition()
  649. self.openDialogs['rectangle'].OnApply(event = None)
  650. self.openDialogs['rectangle'].Destroy()
  651. dlg = RectangleDialog(self, id = id, settings = self.instruction,
  652. type = 'rectangle', coordinates = coordinates)
  653. self.openDialogs['rectangle'] = dlg
  654. if position:
  655. dlg.SetPosition(position)
  656. if coordinates:
  657. dlg.OnApply(event = None)
  658. dlg.Show()
  659. def OnAddLabels(self, event, id = None):
  660. """!Show dialog for labels"""
  661. if self.instruction.FindInstructionByType('labels'):
  662. id = self.instruction.FindInstructionByType('labels').id
  663. else: id = None
  664. if 'labels' not in self.openDialogs:
  665. dlg = LabelsDialog(self, id = id, settings = self.instruction)
  666. self.openDialogs['labels'] = dlg
  667. self.openDialogs['labels'].Show()
  668. def getModifiedTextBounds(self, x, y, textExtent, rotation):
  669. """!computes bounding box of rotated text, not very precisely"""
  670. w, h = textExtent
  671. rotation = float(rotation)/180*pi
  672. H = float(w) * sin(rotation)
  673. W = float(w) * cos(rotation)
  674. X, Y = x, y
  675. if pi/2 < rotation <= 3*pi/2:
  676. X = x + W
  677. if 0 < rotation < pi:
  678. Y = y - H
  679. if rotation == 0:
  680. return wx.Rect(x,y, *textExtent)
  681. else:
  682. return wx.Rect(X, Y, abs(W), abs(H)).Inflate(h,h)
  683. def makePSFont(self, textDict):
  684. """!creates a wx.Font object from selected postscript font. To be
  685. used for estimating bounding rectangle of text"""
  686. fontsize = textDict['fontsize'] * self.canvas.currScale
  687. fontface = textDict['font'].split('-')[0]
  688. try:
  689. fontstyle = textDict['font'].split('-')[1]
  690. except IndexError:
  691. fontstyle = ''
  692. if fontface == "Times":
  693. family = wx.FONTFAMILY_ROMAN
  694. face = "times"
  695. elif fontface == "Helvetica":
  696. family = wx.FONTFAMILY_SWISS
  697. face = 'helvetica'
  698. elif fontface == "Courier":
  699. family = wx.FONTFAMILY_TELETYPE
  700. face = 'courier'
  701. else:
  702. family = wx.FONTFAMILY_DEFAULT
  703. face = ''
  704. style = wx.FONTSTYLE_NORMAL
  705. weight = wx.FONTWEIGHT_NORMAL
  706. if 'Oblique' in fontstyle:
  707. style = wx.FONTSTYLE_SLANT
  708. if 'Italic' in fontstyle:
  709. style = wx.FONTSTYLE_ITALIC
  710. if 'Bold' in fontstyle:
  711. weight = wx.FONTWEIGHT_BOLD
  712. try:
  713. fn = wx.Font(pointSize = fontsize, family = family, style = style,
  714. weight = weight, face = face)
  715. except:
  716. fn = wx.Font(pointSize = fontsize, family = wx.FONTFAMILY_DEFAULT,
  717. style = wx.FONTSTYLE_NORMAL, weight = wx.FONTWEIGHT_NORMAL)
  718. return fn
  719. def getTextExtent(self, textDict):
  720. """!Estimates bounding rectangle of text"""
  721. #fontsize = str(fontsize if fontsize >= 4 else 4)
  722. dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  723. fn = self.makePSFont(textDict)
  724. try:
  725. dc.SetFont(fn)
  726. w,h,lh = dc.GetMultiLineTextExtent(textDict['text'])
  727. return (w,h)
  728. except:
  729. return (0,0)
  730. def getInitMap(self):
  731. """!Create default map frame when no map is selected, needed for coordinates in map units"""
  732. instrFile = grass.tempfile()
  733. instrFileFd = open(instrFile, mode = 'w')
  734. instrFileFd.write(self.InstructionFile())
  735. instrFileFd.flush()
  736. instrFileFd.close()
  737. page = self.instruction.FindInstructionByType('page')
  738. mapInitRect = GetMapBounds(instrFile, portrait = (page['Orientation'] == 'Portrait'))
  739. grass.try_remove(instrFile)
  740. region = grass.region()
  741. units = UnitConversion(self)
  742. realWidth = units.convert(value = abs(region['w'] - region['e']), fromUnit = 'meter', toUnit = 'inch')
  743. scale = mapInitRect.Get()[2]/realWidth
  744. initMap = self.instruction.FindInstructionByType('initMap')
  745. if initMap:
  746. id = initMap.id
  747. else:
  748. id = None
  749. if not id:
  750. id = wx.NewId()
  751. initMap = InitMap(id)
  752. self.instruction.AddInstruction(initMap)
  753. self.instruction[id].SetInstruction(dict(rect = mapInitRect, scale = scale))
  754. def OnDelete(self, event):
  755. if self.canvas.dragId != -1 and self.currentPage == 0:
  756. if self.instruction[self.canvas.dragId].type == 'map':
  757. self.deleteObject(self.canvas.dragId)
  758. self.getInitMap()
  759. self.canvas.RecalculateEN()
  760. else:
  761. self.deleteObject(self.canvas.dragId)
  762. def deleteObject(self, id):
  763. """!Deletes object, his id and redraws"""
  764. #delete from canvas
  765. self.canvas.pdcObj.RemoveId(id)
  766. if id == self.canvas.dragId:
  767. self.canvas.pdcTmp.RemoveAll()
  768. self.canvas.dragId = -1
  769. self.canvas.Refresh()
  770. # delete from instructions
  771. del self.instruction[id]
  772. def DialogDataChanged(self, id):
  773. ids = id
  774. if type(id) == int:
  775. ids = [id]
  776. for id in ids:
  777. itype = self.instruction[id].type
  778. if itype in ('scalebar', 'mapinfo', 'image'):
  779. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  780. self.canvas.UpdateLabel(itype = itype, id = id)
  781. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  782. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  783. self.canvas.RedrawSelectBox(id)
  784. if itype == 'northArrow':
  785. self.canvas.UpdateLabel(itype = itype, id = id)
  786. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  787. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  788. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'bitmap', bb = drawRectangle)
  789. self.canvas.RedrawSelectBox(id)
  790. if itype in ('point', 'line', 'rectangle'):
  791. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  792. # coords only for line
  793. coords = None
  794. if itype == 'line':
  795. point1 = self.instruction[id]['where'][0]
  796. point2 = self.instruction[id]['where'][1]
  797. point1Coords = self.canvas.CanvasPaperCoordinates(rect = Rect2DPS(point1, (0, 0)), canvasToPaper = False)[:2]
  798. point2Coords = self.canvas.CanvasPaperCoordinates(rect = Rect2DPS(point2, (0, 0)), canvasToPaper = False)[:2]
  799. coords = (point1Coords, point2Coords)
  800. # fill color is not in line
  801. fcolor = None
  802. if 'fcolor' in self.instruction[id].GetInstruction():
  803. fcolor = self.instruction[id]['fcolor']
  804. # width is not in point
  805. width = None
  806. if 'width' in self.instruction[id].GetInstruction():
  807. width = self.instruction[id]['width']
  808. self.canvas.DrawGraphics(drawid = id, color = self.instruction[id]['color'], shape = itype,
  809. fcolor = fcolor, width = width, bb = drawRectangle, lineCoords = coords)
  810. self.canvas.RedrawSelectBox(id)
  811. if itype == 'text':
  812. if self.instruction[id]['rotate']:
  813. rot = float(self.instruction[id]['rotate'])
  814. else:
  815. rot = 0
  816. extent = self.getTextExtent(textDict = self.instruction[id].GetInstruction())
  817. rect = Rect2DPS(self.instruction[id]['where'], (0, 0))
  818. self.instruction[id]['coords'] = list(self.canvas.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)[:2])
  819. #computes text coordinates according to reference point, not precisely
  820. if self.instruction[id]['ref'].split()[0] == 'lower':
  821. self.instruction[id]['coords'][1] -= extent[1]
  822. elif self.instruction[id]['ref'].split()[0] == 'center':
  823. self.instruction[id]['coords'][1] -= extent[1]/2
  824. if self.instruction[id]['ref'].split()[1] == 'right':
  825. self.instruction[id]['coords'][0] -= extent[0] * cos(rot/180*pi)
  826. self.instruction[id]['coords'][1] += extent[0] * sin(rot/180*pi)
  827. elif self.instruction[id]['ref'].split()[1] == 'center':
  828. self.instruction[id]['coords'][0] -= extent[0]/2 * cos(rot/180*pi)
  829. self.instruction[id]['coords'][1] += extent[0]/2 * sin(rot/180*pi)
  830. self.instruction[id]['coords'][0] += self.instruction[id]['xoffset']
  831. self.instruction[id]['coords'][1] -= self.instruction[id]['yoffset']
  832. coords = self.instruction[id]['coords']
  833. self.instruction[id]['rect'] = bounds = self.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  834. self.canvas.DrawRotText(pdc = self.canvas.pdcObj, drawId = id,
  835. textDict = self.instruction[id].GetInstruction(),
  836. coords = coords, bounds = bounds)
  837. self.canvas.RedrawSelectBox(id)
  838. if itype in ('map', 'vector', 'raster', 'labels'):
  839. if itype == 'raster':#set resolution
  840. info = grass.raster_info(self.instruction[id]['raster'])
  841. RunCommand('g.region', nsres = info['nsres'], ewres = info['ewres'])
  842. # change current raster in raster legend
  843. if 'rasterLegend' in self.openDialogs:
  844. self.openDialogs['rasterLegend'].updateDialog()
  845. id = self.instruction.FindInstructionByType('map').id
  846. #check resolution
  847. if itype == 'raster':
  848. SetResolution(dpi = self.instruction[id]['resolution'],
  849. width = self.instruction[id]['rect'].width,
  850. height = self.instruction[id]['rect'].height)
  851. rectCanvas = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'],
  852. canvasToPaper = False)
  853. self.canvas.RecalculateEN()
  854. self.canvas.UpdateMapLabel()
  855. self.canvas.Draw(pen = self.pen['map'], brush = self.brush['map'],
  856. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = rectCanvas)
  857. # redraw select box
  858. self.canvas.RedrawSelectBox(id)
  859. self.canvas.pdcTmp.RemoveId(self.canvas.idZoomBoxTmp)
  860. # redraw to get map to the bottom layer
  861. #self.canvas.Zoom(zoomFactor = 1, view = (0, 0))
  862. if itype == 'rasterLegend':
  863. if self.instruction[id]['rLegend']:
  864. self.canvas.UpdateLabel(itype = itype, id = id)
  865. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  866. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  867. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  868. self.canvas.RedrawSelectBox(id)
  869. else:
  870. self.deleteObject(id)
  871. if itype == 'vectorLegend':
  872. if not self.instruction.FindInstructionByType('vector'):
  873. self.deleteObject(id)
  874. elif self.instruction[id]['vLegend']:
  875. self.canvas.UpdateLabel(itype = itype, id = id)
  876. drawRectangle = self.canvas.CanvasPaperCoordinates(rect = self.instruction[id]['rect'], canvasToPaper = False)
  877. self.canvas.Draw(pen = self.pen[itype], brush = self.brush[itype],
  878. pdc = self.canvas.pdcObj, drawid = id, pdctype = 'rectText', bb = drawRectangle)
  879. self.canvas.RedrawSelectBox(id)
  880. else:
  881. self.deleteObject(id)
  882. def OnPageChanged(self, event):
  883. """!Flatnotebook page has changed"""
  884. self.currentPage = self.book.GetPageIndex(self.book.GetCurrentPage())
  885. if self.currentPage == 1:
  886. self.SetStatusText(_("Press button with green triangle icon to generate preview."))
  887. else:
  888. self.SetStatusText('')
  889. def OnPageChanging(self, event):
  890. """!Flatnotebook page is changing"""
  891. if self.currentPage == 0 and self.mouse['use'] == 'addMap':
  892. event.Veto()
  893. def OnHelp(self, event):
  894. """!Show help"""
  895. if self.parent and self.parent.GetName() == 'LayerManager':
  896. log = self.parent.GetLogWindow()
  897. log.RunCmd(['g.manual',
  898. 'entry=wxGUI.psmap'])
  899. else:
  900. RunCommand('g.manual',
  901. quiet = True,
  902. entry = 'wxGUI.psmap')
  903. def OnAbout(self, event):
  904. """!Display About window"""
  905. info = wx.AboutDialogInfo()
  906. info.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  907. info.SetName(_('wxGUI Cartographic Composer'))
  908. info.SetWebSite('http://grass.osgeo.org')
  909. info.SetDescription(_('(C) 2011 by the GRASS Development Team\n\n') +
  910. '\n'.join(textwrap.wrap(_('This program is free software under the GNU General Public License'
  911. '(>=v2). Read the file COPYING that comes with GRASS for details.'), 75)))
  912. wx.AboutBox(info)
  913. def OnCloseWindow(self, event):
  914. """!Close window"""
  915. try:
  916. os.remove(self.imgName)
  917. except OSError:
  918. pass
  919. grass.set_raise_on_error(False)
  920. self.Destroy()
  921. class PsMapBufferedWindow(wx.Window):
  922. """!A buffered window class.
  923. @param parent parent window
  924. @param kwargs other wx.Window parameters
  925. """
  926. def __init__(self, parent, id = wx.ID_ANY,
  927. style = wx.NO_FULL_REPAINT_ON_RESIZE,
  928. **kwargs):
  929. wx.Window.__init__(self, parent, id = id, style = style)
  930. self.parent = parent
  931. self.FitInside()
  932. # store an off screen empty bitmap for saving to file
  933. self._buffer = None
  934. # indicates whether or not a resize event has taken place
  935. self.resize = False
  936. self.mouse = kwargs['mouse']
  937. self.cursors = kwargs['cursors']
  938. self.preview = kwargs['preview']
  939. self.pen = kwargs['pen']
  940. self.brush = kwargs['brush']
  941. if kwargs.has_key('instruction'):
  942. self.instruction = kwargs['instruction']
  943. if kwargs.has_key('openDialogs'):
  944. self.openDialogs = kwargs['openDialogs']
  945. if kwargs.has_key('pageId'):
  946. self.pageId = kwargs['pageId']
  947. if kwargs.has_key('objectId'):
  948. self.objectId = kwargs['objectId']
  949. #labels
  950. self.itemLabelsDict = { 'map': _("MAP FRAME"),
  951. 'rasterLegend': _("RASTER LEGEND"),
  952. 'vectorLegend': _("VECTOR LEGEND"),
  953. 'mapinfo': _("MAP INFO"),
  954. 'scalebar': _("SCALE BAR"),
  955. 'image': _("IMAGE"),
  956. 'northArrow': _("NORTH ARROW")}
  957. self.itemLabels = {}
  958. # define PseudoDC
  959. self.pdc = wx.PseudoDC()
  960. self.pdcObj = wx.PseudoDC()
  961. self.pdcPaper = wx.PseudoDC()
  962. self.pdcTmp = wx.PseudoDC()
  963. self.pdcImage = wx.PseudoDC()
  964. self.SetClientSize((700,510))#?
  965. self._buffer = wx.EmptyBitmap(*self.GetClientSize())
  966. self.idBoxTmp = wx.NewId()
  967. self.idZoomBoxTmp = wx.NewId()
  968. self.idResizeBoxTmp = wx.NewId()
  969. self.idLinePointsTmp = (wx.NewId(), wx.NewId()) # ids of marks for moving line vertices
  970. self.resizeBoxSize = wx.Size(8, 8)
  971. self.showResizeHelp = False # helper for correctly working statusbar
  972. self.dragId = -1
  973. if self.preview:
  974. self.image = None
  975. self.imageId = 2000
  976. self.imgName = self.parent.imgName
  977. self.currScale = None
  978. self.Clear()
  979. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
  980. self.Bind(wx.EVT_PAINT, self.OnPaint)
  981. self.Bind(wx.EVT_SIZE, self.OnSize)
  982. self.Bind(wx.EVT_IDLE, self.OnIdle)
  983. # self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
  984. self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
  985. def Clear(self):
  986. """!Clear canvas and set paper
  987. """
  988. bg = wx.LIGHT_GREY_BRUSH
  989. self.pdcPaper.BeginDrawing()
  990. self.pdcPaper.SetBackground(bg)
  991. self.pdcPaper.Clear()
  992. self.pdcPaper.EndDrawing()
  993. self.pdcObj.RemoveAll()
  994. self.pdcTmp.RemoveAll()
  995. if not self.preview:
  996. self.SetPage()
  997. def CanvasPaperCoordinates(self, rect, canvasToPaper = True):
  998. """!Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa"""
  999. units = UnitConversion(self)
  1000. fromU = 'pixel'
  1001. toU = 'inch'
  1002. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1003. pRectx, pRecty = pRect.x, pRect.y
  1004. scale = 1/self.currScale
  1005. if not canvasToPaper: # paper -> canvas
  1006. fromU = 'inch'
  1007. toU = 'pixel'
  1008. scale = self.currScale
  1009. pRectx = units.convert(value = - pRect.x, fromUnit = 'pixel', toUnit = 'inch' ) /scale #inch, real, negative
  1010. pRecty = units.convert(value = - pRect.y, fromUnit = 'pixel', toUnit = 'inch' ) /scale
  1011. Width = units.convert(value = rect.GetWidth(), fromUnit = fromU, toUnit = toU) * scale
  1012. Height = units.convert(value = rect.GetHeight(), fromUnit = fromU, toUnit = toU) * scale
  1013. X = units.convert(value = (rect.GetX() - pRectx), fromUnit = fromU, toUnit = toU) * scale
  1014. Y = units.convert(value = (rect.GetY() - pRecty), fromUnit = fromU, toUnit = toU) * scale
  1015. return Rect2D(X, Y, Width, Height)
  1016. def SetPage(self):
  1017. """!Sets and changes page, redraws paper"""
  1018. page = self.instruction[self.pageId]
  1019. if not page:
  1020. page = PageSetup(id = self.pageId)
  1021. self.instruction.AddInstruction(page)
  1022. ppi = wx.ClientDC(self).GetPPI()
  1023. cW, cH = self.GetClientSize()
  1024. pW, pH = page['Width']*ppi[0], page['Height']*ppi[1]
  1025. if self.currScale is None:
  1026. self.currScale = min(cW/pW, cH/pH)
  1027. pW = pW * self.currScale
  1028. pH = pH * self.currScale
  1029. x = cW/2 - pW/2
  1030. y = cH/2 - pH/2
  1031. self.DrawPaper(wx.Rect(x, y, pW, pH))
  1032. def modifyRectangle(self, r):
  1033. """! Recalculates rectangle not to have negative size"""
  1034. if r.GetWidth() < 0:
  1035. r.SetX(r.GetX() + r.GetWidth())
  1036. if r.GetHeight() < 0:
  1037. r.SetY(r.GetY() + r.GetHeight())
  1038. r.SetWidth(abs(r.GetWidth()))
  1039. r.SetHeight(abs(r.GetHeight()))
  1040. return r
  1041. def RecalculateEN(self):
  1042. """!Recalculate east and north for texts (eps, points) after their or map's movement"""
  1043. try:
  1044. mapId = self.instruction.FindInstructionByType('map').id
  1045. except AttributeError:
  1046. mapId = self.instruction.FindInstructionByType('initMap').id
  1047. for itemType in ('text', 'image', 'northArrow', 'point', 'line', 'rectangle'):
  1048. items = self.instruction.FindInstructionByType(itemType, list = True)
  1049. for item in items:
  1050. instr = self.instruction[item.id]
  1051. if itemType in ('line', 'rectangle'):
  1052. if itemType == 'line':
  1053. e1, n1 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][0][0],
  1054. y = instr['where'][0][1], paperToMap = True)
  1055. e2, n2 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][1][0],
  1056. y = instr['where'][1][1], paperToMap = True)
  1057. else:
  1058. e1, n1 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['rect'].GetLeft(),
  1059. y = instr['rect'].GetTop(), paperToMap = True)
  1060. e2, n2 = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['rect'].GetRight(),
  1061. y = instr['rect'].GetBottom(), paperToMap = True)
  1062. instr['east1'] = e1
  1063. instr['north1'] = n1
  1064. instr['east2'] = e2
  1065. instr['north2'] = n2
  1066. else:
  1067. e, n = PaperMapCoordinates(mapInstr = self.instruction[mapId], x = instr['where'][0],
  1068. y = instr['where'][1], paperToMap = True)
  1069. instr['east'], instr['north'] = e, n
  1070. def OnPaint(self, event):
  1071. """!Draw pseudo DC to buffer
  1072. """
  1073. if not self._buffer:
  1074. return
  1075. dc = wx.BufferedPaintDC(self, self._buffer)
  1076. # use PrepareDC to set position correctly
  1077. # probably does nothing, removed from wxPython 2.9
  1078. # self.PrepareDC(dc)
  1079. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  1080. dc.Clear()
  1081. # draw paper
  1082. if not self.preview:
  1083. self.pdcPaper.DrawToDC(dc)
  1084. # draw to the DC using the calculated clipping rect
  1085. rgn = self.GetUpdateRegion()
  1086. if not self.preview:
  1087. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  1088. else:
  1089. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  1090. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  1091. def MouseActions(self, event):
  1092. """!Mouse motion and button click notifier
  1093. """
  1094. # zoom with mouse wheel
  1095. if event.GetWheelRotation() != 0:
  1096. self.OnMouseWheel(event)
  1097. # left mouse button pressed
  1098. elif event.LeftDown():
  1099. self.OnLeftDown(event)
  1100. # left mouse button released
  1101. elif event.LeftUp():
  1102. self.OnLeftUp(event)
  1103. # dragging
  1104. elif event.Dragging():
  1105. self.OnDragging(event)
  1106. # double click
  1107. elif event.ButtonDClick():
  1108. self.OnButtonDClick(event)
  1109. # middle mouse button pressed
  1110. elif event.MiddleDown():
  1111. self.OnMiddleDown(event)
  1112. elif event.Moving():
  1113. self.OnMouseMoving(event)
  1114. def OnMouseWheel(self, event):
  1115. """!Mouse wheel scrolled.
  1116. Changes zoom."""
  1117. if UserSettings.Get(group = 'display',
  1118. key = 'mouseWheelZoom',
  1119. subkey = 'selection') == 2:
  1120. event.Skip()
  1121. return
  1122. zoom = event.GetWheelRotation()
  1123. oldUse = self.mouse['use']
  1124. self.mouse['begin'] = event.GetPosition()
  1125. if UserSettings.Get(group = 'display',
  1126. key = 'scrollDirection',
  1127. subkey = 'selection'):
  1128. zoom *= -1
  1129. if zoom > 0:
  1130. self.mouse['use'] = 'zoomin'
  1131. else:
  1132. self.mouse['use'] = 'zoomout'
  1133. zoomFactor, view = self.ComputeZoom(wx.Rect(0, 0, 0, 0))
  1134. self.Zoom(zoomFactor, view)
  1135. self.mouse['use'] = oldUse
  1136. def OnMouseMoving(self, event):
  1137. """!Mouse cursor moving.
  1138. Change cursor when moving over resize marker.
  1139. """
  1140. if self.preview:
  1141. return
  1142. if self.mouse['use'] in ('pointer', 'resize'):
  1143. pos = event.GetPosition()
  1144. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  1145. if foundResize and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1146. self.SetCursor(self.cursors["sizenwse"])
  1147. self.parent.SetStatusText(_('Click and drag to resize object'), 0)
  1148. self.showResizeHelp = True
  1149. else:
  1150. if self.showResizeHelp:
  1151. self.parent.SetStatusText('', 0)
  1152. self.SetCursor(self.cursors["default"])
  1153. self.showResizeHelp = False
  1154. def OnLeftDown(self, event):
  1155. """!Left mouse button pressed.
  1156. Select objects, redraw, prepare for moving/resizing.
  1157. """
  1158. self.mouse['begin'] = event.GetPosition()
  1159. self.begin = self.mouse['begin']
  1160. # select
  1161. if self.mouse['use'] == 'pointer':
  1162. found = self.pdcObj.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1163. foundResize = self.pdcTmp.FindObjects(self.mouse['begin'][0], self.mouse['begin'][1])
  1164. if foundResize and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp:
  1165. self.mouse['use'] = 'resize'
  1166. # when resizing, proportions match region
  1167. if self.instruction[self.dragId].type == 'map':
  1168. self.constraint = False
  1169. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1170. if self.instruction[self.dragId]['scaleType'] in (0, 1, 2):
  1171. self.constraint = True
  1172. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1173. if self.instruction[self.dragId].type == 'line':
  1174. self.currentLinePoint = self.idLinePointsTmp.index(foundResize[0])
  1175. elif found:
  1176. self.dragId = found[0]
  1177. self.RedrawSelectBox(self.dragId)
  1178. if self.instruction[self.dragId].type not in ('map', 'rectangle'):
  1179. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1180. self.Refresh()
  1181. if self.instruction[self.dragId].type != 'line':
  1182. for id in self.idLinePointsTmp:
  1183. self.pdcTmp.RemoveId(id)
  1184. self.Refresh()
  1185. else:
  1186. self.dragId = -1
  1187. self.pdcTmp.RemoveId(self.idBoxTmp)
  1188. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1189. for id in self.idLinePointsTmp:
  1190. self.pdcTmp.RemoveId(id)
  1191. self.Refresh()
  1192. def OnLeftUp(self, event):
  1193. """!Left mouse button released.
  1194. Recalculate zooming/resizing/moving and redraw.
  1195. """
  1196. # zoom in, zoom out
  1197. if self.mouse['use'] in ('zoomin','zoomout'):
  1198. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1199. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1200. self.Refresh()
  1201. zoomFactor, view = self.ComputeZoom(zoomR)
  1202. self.Zoom(zoomFactor, view)
  1203. # draw map frame
  1204. if self.mouse['use'] == 'addMap':
  1205. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1206. # too small rectangle, it's usually some mistake
  1207. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1208. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1209. self.Refresh()
  1210. return
  1211. rectPaper = self.CanvasPaperCoordinates(rect = rectTmp, canvasToPaper = True)
  1212. dlg = MapDialog(parent = self.parent, id = [None, None, None], settings = self.instruction,
  1213. rect = rectPaper)
  1214. self.openDialogs['map'] = dlg
  1215. self.openDialogs['map'].Show()
  1216. self.mouse['use'] = self.parent.mouseOld
  1217. self.SetCursor(self.parent.cursorOld)
  1218. self.parent.toolbar.ToggleTool(self.parent.actionOld, True)
  1219. self.parent.toolbar.ToggleTool(self.parent.toolbar.action['id'], False)
  1220. self.parent.toolbar.action['id'] = self.parent.actionOld
  1221. return
  1222. # resize resizable objects (map, line, rectangle)
  1223. if self.mouse['use'] == 'resize':
  1224. mapObj = self.instruction.FindInstructionByType('map')
  1225. if not mapObj:
  1226. mapObj = self.instruction.FindInstructionByType('initMap')
  1227. mapId = mapObj.id
  1228. if self.dragId == mapId:
  1229. # necessary to change either map frame (scaleType 0,1,2) or region (scaletype 3)
  1230. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1231. newRectPaper = self.CanvasPaperCoordinates(rect = newRectCanvas, canvasToPaper = True)
  1232. self.instruction[mapId]['rect'] = newRectPaper
  1233. if self.instruction[mapId]['scaleType'] in (0, 1, 2):
  1234. if self.instruction[mapId]['scaleType'] == 0:
  1235. scale, foo, rect = AutoAdjust(self, scaleType = 0,
  1236. map = self.instruction[mapId]['map'],
  1237. mapType = self.instruction[mapId]['mapType'],
  1238. rect = self.instruction[mapId]['rect'])
  1239. elif self.instruction[mapId]['scaleType'] == 1:
  1240. scale, foo, rect = AutoAdjust(self, scaleType = 1,
  1241. region = self.instruction[mapId]['region'],
  1242. rect = self.instruction[mapId]['rect'])
  1243. else:
  1244. scale, foo, rect = AutoAdjust(self, scaleType = 2,
  1245. rect = self.instruction[mapId]['rect'])
  1246. self.instruction[mapId]['rect'] = rect
  1247. self.instruction[mapId]['scale'] = scale
  1248. rectCanvas = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = False)
  1249. self.Draw(pen = self.pen['map'], brush = self.brush['map'],
  1250. pdc = self.pdcObj, drawid = mapId, pdctype = 'rectText', bb = rectCanvas)
  1251. elif self.instruction[mapId]['scaleType'] == 3:
  1252. ComputeSetRegion(self, mapDict = self.instruction[mapId].GetInstruction())
  1253. #check resolution
  1254. SetResolution(dpi = self.instruction[mapId]['resolution'],
  1255. width = self.instruction[mapId]['rect'].width,
  1256. height = self.instruction[mapId]['rect'].height)
  1257. self.RedrawSelectBox(mapId)
  1258. self.Zoom(zoomFactor = 1, view = (0, 0))
  1259. elif self.instruction[self.dragId].type == 'line':
  1260. points = self.instruction[self.dragId]['where']
  1261. self.instruction[self.dragId]['rect'] = Rect2DPP(points[0], points[1])
  1262. self.RecalculatePosition(ids = [self.dragId])
  1263. elif self.instruction[self.dragId].type == 'rectangle':
  1264. self.RecalculatePosition(ids = [self.dragId])
  1265. self.mouse['use'] = 'pointer'
  1266. # recalculate the position of objects after dragging
  1267. if self.mouse['use'] in ('pointer', 'resize') and self.dragId != -1:
  1268. if self.mouse['begin'] != event.GetPosition(): #for double click
  1269. self.RecalculatePosition(ids = [self.dragId])
  1270. if self.instruction[self.dragId].type in self.openDialogs:
  1271. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1272. elif self.mouse['use'] in ('addPoint', 'addLine', 'addRectangle'):
  1273. endCoordinates = self.CanvasPaperCoordinates(rect = wx.Rect(event.GetX(), event.GetY(), 0, 0),
  1274. canvasToPaper = True)[:2]
  1275. diffX = event.GetX() - self.mouse['begin'][0]
  1276. diffY = event.GetY() - self.mouse['begin'][1]
  1277. if self.mouse['use'] == 'addPoint':
  1278. self.parent.AddPoint(coordinates = endCoordinates)
  1279. elif self.mouse['use'] in ('addLine', 'addRectangle'):
  1280. # not too small lines/rectangles
  1281. if sqrt(diffX * diffX + diffY * diffY) < 5:
  1282. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1283. self.Refresh()
  1284. return
  1285. beginCoordinates = self.CanvasPaperCoordinates(rect = wx.Rect(self.mouse['begin'][0],
  1286. self.mouse['begin'][1], 0, 0),
  1287. canvasToPaper = True)[:2]
  1288. if self.mouse['use'] == 'addLine':
  1289. self.parent.AddLine(coordinates = [beginCoordinates, endCoordinates])
  1290. else:
  1291. self.parent.AddRectangle(coordinates = [beginCoordinates, endCoordinates])
  1292. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1293. self.Refresh()
  1294. def OnButtonDClick(self, event):
  1295. """!Open object dialog for editing."""
  1296. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1297. itemCall = {'text':self.parent.OnAddText,
  1298. 'mapinfo': self.parent.OnAddMapinfo,
  1299. 'scalebar': self.parent.OnAddScalebar,
  1300. 'image': self.parent.OnAddImage,
  1301. 'northArrow' : self.parent.OnAddNorthArrow,
  1302. 'point': self.parent.AddPoint,
  1303. 'line': self.parent.AddLine,
  1304. 'rectangle': self.parent.AddRectangle,
  1305. 'rasterLegend': self.parent.OnAddLegend,
  1306. 'vectorLegend': self.parent.OnAddLegend,
  1307. 'map': self.parent.OnAddMap}
  1308. itemArg = { 'text': dict(event = None, id = self.dragId),
  1309. 'mapinfo': dict(event = None),
  1310. 'scalebar': dict(event = None),
  1311. 'image': dict(event = None, id = self.dragId),
  1312. 'northArrow': dict(event = None, id = self.dragId),
  1313. 'point': dict(id = self.dragId),
  1314. 'line': dict(id = self.dragId),
  1315. 'rectangle': dict(id = self.dragId),
  1316. 'rasterLegend': dict(event = None),
  1317. 'vectorLegend': dict(event = None, page = 1),
  1318. 'map': dict(event = None, notebook = True)}
  1319. type = self.instruction[self.dragId].type
  1320. itemCall[type](**itemArg[type])
  1321. def OnDragging(self, event):
  1322. """!Process panning/resizing/drawing/moving."""
  1323. if event.MiddleIsDown():
  1324. # panning
  1325. self.mouse['end'] = event.GetPosition()
  1326. self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
  1327. self.mouse['begin'] = event.GetPosition()
  1328. elif event.LeftIsDown():
  1329. # draw box when zooming, creating map
  1330. if self.mouse['use'] in ('zoomin', 'zoomout', 'addMap', 'addLine', 'addRectangle'):
  1331. self.mouse['end'] = event.GetPosition()
  1332. r = wx.Rect(self.mouse['begin'][0], self.mouse['begin'][1],
  1333. self.mouse['end'][0]-self.mouse['begin'][0], self.mouse['end'][1]-self.mouse['begin'][1])
  1334. r = self.modifyRectangle(r)
  1335. if self.mouse['use'] in ('addLine', 'addRectangle'):
  1336. if self.mouse['use'] == 'addLine':
  1337. pdcType = 'line'
  1338. lineCoords = (self.mouse['begin'], self.mouse['end'])
  1339. else:
  1340. pdcType = 'rect'
  1341. lineCoords = None
  1342. if r[2] < 2 or r[3] < 2:
  1343. # to avoid strange behavoiur
  1344. return
  1345. self.Draw(pen = self.pen['line'], brush = self.brush['line'],
  1346. pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1347. pdctype = pdcType, bb = r, lineCoords = lineCoords)
  1348. else:
  1349. self.Draw(pen = self.pen['box'], brush = self.brush['box'],
  1350. pdc = self.pdcTmp, drawid = self.idZoomBoxTmp,
  1351. pdctype = 'rect', bb = r)
  1352. # panning
  1353. if self.mouse["use"] == 'pan':
  1354. self.mouse['end'] = event.GetPosition()
  1355. self.Pan(begin = self.mouse['begin'], end = self.mouse['end'])
  1356. self.mouse['begin'] = event.GetPosition()
  1357. # move object
  1358. if self.mouse['use'] == 'pointer' and self.dragId != -1:
  1359. self.mouse['end'] = event.GetPosition()
  1360. dx, dy = self.mouse['end'][0] - self.begin[0], self.mouse['end'][1] - self.begin[1]
  1361. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1362. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1363. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1364. for id in self.idLinePointsTmp:
  1365. self.pdcTmp.TranslateId(id, dx, dy)
  1366. if self.instruction[self.dragId].type == 'text':
  1367. self.instruction[self.dragId]['coords'] = self.instruction[self.dragId]['coords'][0] + dx,\
  1368. self.instruction[self.dragId]['coords'][1] + dy
  1369. self.begin = event.GetPosition()
  1370. self.Refresh()
  1371. # resize object
  1372. if self.mouse['use'] == 'resize':
  1373. pos = event.GetPosition()
  1374. diffX = pos[0] - self.mouse['begin'][0]
  1375. diffY = pos[1] - self.mouse['begin'][1]
  1376. if self.instruction[self.dragId].type == 'map':
  1377. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1378. width, height = self.mapBounds.GetWidth(), self.mapBounds.GetHeight()
  1379. # match given region
  1380. if self.constraint:
  1381. if width > height:
  1382. newWidth = width + diffX
  1383. newHeight = height + diffX * (float(height) / width)
  1384. else:
  1385. newWidth = width + diffY * (float(width) / height)
  1386. newHeight = height + diffY
  1387. else:
  1388. newWidth = width + diffX
  1389. newHeight = height + diffY
  1390. if newWidth < 10 or newHeight < 10:
  1391. return
  1392. bounds = wx.Rect(x, y, newWidth, newHeight)
  1393. self.Draw(pen = self.pen['map'], brush = self.brush['map'], pdc = self.pdcObj, drawid = self.dragId,
  1394. pdctype = 'rectText', bb = bounds)
  1395. elif self.instruction[self.dragId].type == 'rectangle':
  1396. instr = self.instruction[self.dragId]
  1397. rect = self.CanvasPaperCoordinates(rect = instr['rect'], canvasToPaper = False)
  1398. rect.SetWidth(rect.GetWidth() + diffX)
  1399. rect.SetHeight(rect.GetHeight() + diffY)
  1400. if rect.GetWidth() < 5 or rect.GetHeight() < 5:
  1401. return
  1402. self.DrawGraphics(drawid = self.dragId, shape = 'rectangle', color = instr['color'],
  1403. fcolor = instr['fcolor'], width = instr['width'], bb = rect)
  1404. elif self.instruction[self.dragId].type == 'line':
  1405. instr = self.instruction[self.dragId]
  1406. points = instr['where']
  1407. # moving point
  1408. if self.currentLinePoint == 0:
  1409. pPaper = points[1]
  1410. else:
  1411. pPaper = points[0]
  1412. pCanvas = self.CanvasPaperCoordinates(rect = Rect2DPS(pPaper, (0, 0)),
  1413. canvasToPaper = False)[:2]
  1414. bounds = wx.RectPP(pCanvas, pos)
  1415. self.DrawGraphics(drawid = self.dragId, shape = 'line', color = instr['color'],
  1416. width = instr['width'], bb = bounds, lineCoords = (pos, pCanvas))
  1417. # update paper coordinates
  1418. points[self.currentLinePoint] = self.CanvasPaperCoordinates(rect = wx.RectPS(pos, (0, 0)),
  1419. canvasToPaper = True)[:2]
  1420. self.RedrawSelectBox(self.dragId)
  1421. def OnMiddleDown(self, event):
  1422. """!Middle mouse button pressed."""
  1423. self.mouse['begin'] = event.GetPosition()
  1424. def Pan(self, begin, end):
  1425. """!Move canvas while dragging.
  1426. @param begin x,y coordinates of first point
  1427. @param end x,y coordinates of second point
  1428. """
  1429. view = begin[0] - end[0], begin[1] - end[1]
  1430. zoomFactor = 1
  1431. self.Zoom(zoomFactor, view)
  1432. def RecalculatePosition(self, ids):
  1433. for id in ids:
  1434. itype = self.instruction[id].type
  1435. if itype in ('map', 'rectangle'):
  1436. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1437. canvasToPaper = True)
  1438. self.RecalculateEN()
  1439. elif itype in ('mapinfo' ,'rasterLegend', 'vectorLegend', 'image', 'northArrow'):
  1440. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1441. canvasToPaper = True)
  1442. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1443. canvasToPaper = True)[:2]
  1444. if itype in ('image', 'northArrow'):
  1445. self.RecalculateEN()
  1446. elif itype == 'point':
  1447. rect = self.pdcObj.GetIdBounds(id)
  1448. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = rect,
  1449. canvasToPaper = True)
  1450. rect.OffsetXY(rect.GetWidth()/2, rect.GetHeight()/2)
  1451. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = rect,
  1452. canvasToPaper = True)[:2]
  1453. self.RecalculateEN()
  1454. elif itype == 'line':
  1455. rect = self.pdcObj.GetIdBounds(id)
  1456. oldRect = self.instruction[id]['rect']
  1457. newRect = self.CanvasPaperCoordinates(rect = rect, canvasToPaper = True)
  1458. xDiff = newRect[0] - oldRect[0]
  1459. yDiff = newRect[1] - oldRect[1]
  1460. self.instruction[id]['rect'] = newRect
  1461. point1 = wx.Point2D(xDiff, yDiff) + self.instruction[id]['where'][0]
  1462. point2 = wx.Point2D(xDiff, yDiff) + self.instruction[id]['where'][1]
  1463. self.instruction[id]['where'] = [point1, point2]
  1464. self.RecalculateEN()
  1465. elif itype == 'scalebar':
  1466. self.instruction[id]['rect'] = self.CanvasPaperCoordinates(rect = self.pdcObj.GetIdBounds(id),
  1467. canvasToPaper = True)
  1468. self.instruction[id]['where'] = self.instruction[id]['rect'].GetCentre()
  1469. elif itype == 'text':
  1470. x, y = self.instruction[id]['coords'][0] - self.instruction[id]['xoffset'],\
  1471. self.instruction[id]['coords'][1] + self.instruction[id]['yoffset']
  1472. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1473. if self.instruction[id]['rotate'] is not None:
  1474. rot = float(self.instruction[id]['rotate'])/180*pi
  1475. else:
  1476. rot = 0
  1477. if self.instruction[id]['ref'].split()[0] == 'lower':
  1478. y += extent[1]
  1479. elif self.instruction[id]['ref'].split()[0] == 'center':
  1480. y += extent[1]/2
  1481. if self.instruction[id]['ref'].split()[1] == 'right':
  1482. x += extent[0] * cos(rot)
  1483. y -= extent[0] * sin(rot)
  1484. elif self.instruction[id]['ref'].split()[1] == 'center':
  1485. x += extent[0]/2 * cos(rot)
  1486. y -= extent[0]/2 * sin(rot)
  1487. self.instruction[id]['where'] = self.CanvasPaperCoordinates(rect = Rect2D(x, y, 0, 0),
  1488. canvasToPaper = True)[:2]
  1489. self.RecalculateEN()
  1490. def ComputeZoom(self, rect):
  1491. """!Computes zoom factor and scroll view"""
  1492. zoomFactor = 1
  1493. cW, cH = self.GetClientSize()
  1494. cW = float(cW)
  1495. if rect.IsEmpty(): # clicked on canvas
  1496. zoomFactor = 1.5
  1497. if self.mouse['use'] == 'zoomout':
  1498. zoomFactor = 1./zoomFactor
  1499. x,y = self.mouse['begin']
  1500. xView = x - x/zoomFactor#x - cW/(zoomFactor * 2)
  1501. yView = y - y/zoomFactor#y - cH/(zoomFactor * 2)
  1502. else: #dragging
  1503. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1504. try:
  1505. zoomFactor = 1/max(rW/cW, rH/cH)
  1506. except ZeroDivisionError:
  1507. zoomFactor = 1
  1508. # when zooming to full extent, in some cases, there was zoom 1.01..., which causes problem
  1509. if abs(zoomFactor - 1) > 0.01:
  1510. zoomFactor = zoomFactor
  1511. else:
  1512. zoomFactor = 1.
  1513. if self.mouse['use'] == 'zoomout':
  1514. zoomFactor = min(rW/cW, rH/cH)
  1515. try:
  1516. if rW/rH > cW/cH:
  1517. yView = rect.GetY() - (rW*(cH/cW) - rH)/2
  1518. xView = rect.GetX()
  1519. if self.mouse['use'] == 'zoomout':
  1520. x,y = rect.GetX() + (rW-(cW/cH)*rH)/2, rect.GetY()
  1521. xView, yView = -x, -y
  1522. else:
  1523. xView = rect.GetX() - (rH*(cW/cH) - rW)/2
  1524. yView = rect.GetY()
  1525. if self.mouse['use'] == 'zoomout':
  1526. x,y = rect.GetX(), rect.GetY() + (rH-(cH/cW)*rW)/2
  1527. xView, yView = -x, -y
  1528. except ZeroDivisionError:
  1529. xView, yView = rect.GetX(), rect.GetY()
  1530. return zoomFactor, (int(xView), int(yView))
  1531. def Zoom(self, zoomFactor, view):
  1532. """! Zoom to specified region, scroll view, redraw"""
  1533. if not self.currScale:
  1534. return
  1535. self.currScale = self.currScale*zoomFactor
  1536. if self.currScale > 10 or self.currScale < 0.1:
  1537. self.currScale = self.currScale/zoomFactor
  1538. return
  1539. if not self.preview:
  1540. # redraw paper
  1541. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1542. pRect.OffsetXY(-view[0], -view[1])
  1543. pRect = self.ScaleRect(rect = pRect, scale = zoomFactor)
  1544. self.DrawPaper(pRect)
  1545. #redraw objects
  1546. for id in self.objectId:
  1547. type = self.instruction[id].type
  1548. if type == 'labels': # why it's here? it should not
  1549. continue
  1550. oRect = self.CanvasPaperCoordinates(
  1551. rect = self.instruction[id]['rect'], canvasToPaper = False)
  1552. if type == 'text':
  1553. coords = self.instruction[id]['coords']# recalculate coordinates, they are not equal to BB
  1554. self.instruction[id]['coords'] = coords = [(int(coord) - view[i]) * zoomFactor
  1555. for i, coord in enumerate(coords)]
  1556. self.DrawRotText(pdc = self.pdcObj, drawId = id, textDict = self.instruction[id],
  1557. coords = coords, bounds = oRect )
  1558. extent = self.parent.getTextExtent(textDict = self.instruction[id])
  1559. if self.instruction[id]['rotate']:
  1560. rot = float(self.instruction[id]['rotate'])
  1561. else:
  1562. rot = 0
  1563. self.instruction[id]['rect'] = bounds = self.parent.getModifiedTextBounds(coords[0], coords[1], extent, rot)
  1564. self.pdcObj.SetIdBounds(id, bounds)
  1565. elif type == 'northArrow':
  1566. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1567. drawid = id, pdctype = 'bitmap', bb = oRect)
  1568. elif type in ('point', 'line', 'rectangle'):
  1569. instr = self.instruction[id]
  1570. color = self.instruction[id]['color']
  1571. width = fcolor = coords = None
  1572. if type in ('point', 'rectangle'):
  1573. fcolor = self.instruction[id]['fcolor']
  1574. if type in ('line', 'rectangle'):
  1575. width = self.instruction[id]['width']
  1576. if type in ('line'):
  1577. point1, point2 = instr['where'][0], instr['where'][1]
  1578. point1 = self.CanvasPaperCoordinates(rect = Rect2DPS(point1, (0, 0)),
  1579. canvasToPaper = False)[:2]
  1580. point2 = self.CanvasPaperCoordinates(rect = Rect2DPS(point2, (0, 0)),
  1581. canvasToPaper = False)[:2]
  1582. coords = (point1, point2)
  1583. self.DrawGraphics(drawid = id, shape = type, bb = oRect, lineCoords = coords,
  1584. color = color, fcolor = fcolor, width = width)
  1585. else:
  1586. self.Draw(pen = self.pen[type], brush = self.brush[type], pdc = self.pdcObj,
  1587. drawid = id, pdctype = 'rectText', bb = oRect)
  1588. #redraw tmp objects
  1589. if self.dragId != -1:
  1590. self.RedrawSelectBox(self.dragId)
  1591. #redraw preview
  1592. else: # preview mode
  1593. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  1594. imageRect.OffsetXY(-view[0], -view[1])
  1595. imageRect = self.ScaleRect(rect = imageRect, scale = zoomFactor)
  1596. self.DrawImage(imageRect)
  1597. def ZoomAll(self):
  1598. """! Zoom to full extent"""
  1599. if not self.preview:
  1600. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  1601. else:
  1602. bounds = self.pdcImage.GetIdBounds(self.imageId)
  1603. zoomP = bounds.Inflate(bounds.width/20, bounds.height/20)
  1604. zoomFactor, view = self.ComputeZoom(zoomP)
  1605. self.Zoom(zoomFactor, view)
  1606. def Draw(self, pen, brush, pdc, drawid = None, pdctype = 'rect', bb = wx.Rect(0,0,0,0), lineCoords = None):
  1607. """! Draw object with given pen and brush.
  1608. @param pdc PseudoDC
  1609. @param pdctype 'bitmap'/'rectText'/'rect'/'point'/'line'
  1610. @param bb bounding box
  1611. @param lineCoords coordinates of line start, end points (wx.Point, wx.Point)
  1612. """
  1613. if drawid is None:
  1614. drawid = wx.NewId()
  1615. bb = bb.Get()
  1616. pdc.BeginDrawing()
  1617. pdc.RemoveId(drawid)
  1618. pdc.SetId(drawid)
  1619. pdc.SetPen(pen)
  1620. pdc.SetBrush(brush)
  1621. if pdctype == 'bitmap':
  1622. if havePILImage:
  1623. file = self.instruction[drawid]['epsfile']
  1624. rotation = self.instruction[drawid]['rotate']
  1625. self.DrawBitmap(pdc = pdc, filePath = file, rotation = rotation, bbox = bb)
  1626. else: # draw only rectangle with label
  1627. pdctype = 'rectText'
  1628. if pdctype in ('rect', 'rectText'):
  1629. pdc.DrawRectangle(*bb)
  1630. if pdctype == 'rectText':
  1631. dc = wx.ClientDC(self) # dc created because of method GetTextExtent, which pseudoDC lacks
  1632. font = dc.GetFont()
  1633. size = 10
  1634. font.SetPointSize(size)
  1635. font.SetStyle(wx.ITALIC)
  1636. dc.SetFont(font)
  1637. pdc.SetFont(font)
  1638. text = '\n'.join(self.itemLabels[drawid])
  1639. w,h,lh = dc.GetMultiLineTextExtent(text)
  1640. textExtent = (w,h)
  1641. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1642. r = map(int, bb)
  1643. while not wx.Rect(*r).ContainsRect(textRect) and size >= 8:
  1644. size -= 2
  1645. font.SetPointSize(size)
  1646. dc.SetFont(font)
  1647. pdc.SetFont(font)
  1648. textExtent = dc.GetTextExtent(text)
  1649. textRect = wx.Rect(0, 0, *textExtent).CenterIn(bb)
  1650. pdc.SetTextForeground(wx.Colour(100,100,100,200))
  1651. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1652. pdc.DrawLabel(text = text, rect = textRect)
  1653. elif pdctype == 'point':
  1654. pdc.DrawCircle(x = bb[0] + bb[2] / 2,
  1655. y = bb[1] + bb[3] / 2,
  1656. radius = bb[2] / 2)
  1657. elif pdctype == 'line':
  1658. pdc.DrawLinePoint(lineCoords[0], lineCoords[1])
  1659. pdc.SetIdBounds(drawid, bb)
  1660. pdc.EndDrawing()
  1661. self.Refresh()
  1662. return drawid
  1663. def DrawGraphics(self, drawid, shape, color, bb, width = None, fcolor = None, lineCoords = None):
  1664. """!Draw point/line/rectangle with given color and width
  1665. @param drawid id of drawn object
  1666. @param shape drawn shape: 'point'/'line'/'rectangle'
  1667. @param color pen outline color ('RRR:GGG:BBB')
  1668. @param fcolor brush fill color, if meaningful ('RRR:GGG:BBB')
  1669. @param width pen width
  1670. @param bb bounding box
  1671. @param lineCoords line coordinates (for line only)
  1672. """
  1673. pdctype = {'point' : 'point',
  1674. 'line' : 'line',
  1675. 'rectangle' : 'rect'}
  1676. if color == 'none':
  1677. pen = wx.TRANSPARENT_PEN
  1678. else:
  1679. if width is not None:
  1680. units = UnitConversion(self)
  1681. width = int(units.convert(value = width, fromUnit = 'point', toUnit = 'pixel') * self.currScale)
  1682. else:
  1683. width = 2
  1684. pen = wx.Pen(colour = convertRGB(color), width = width)
  1685. pen.SetCap(wx.CAP_BUTT) # this is how ps.map draws
  1686. brush = wx.TRANSPARENT_BRUSH
  1687. if fcolor and fcolor != 'none':
  1688. brush = wx.Brush(colour = convertRGB(fcolor))
  1689. self.Draw(pen = pen, brush = brush, pdc = self.pdcObj, pdctype = pdctype[shape],
  1690. drawid = drawid, bb = bb, lineCoords = lineCoords)
  1691. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  1692. """!Draw bitmap using PIL"""
  1693. pImg = PILImage.open(filePath)
  1694. if rotation:
  1695. # get rid of black background
  1696. pImg = pImg.convert("RGBA")
  1697. rot = pImg.rotate(rotation, expand = 1)
  1698. new = PILImage.new('RGBA', rot.size, (255,) * 4)
  1699. pImg = PILImage.composite(rot, new, rot)
  1700. pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample = PILImage.BICUBIC)
  1701. img = PilImageToWxImage(pImg)
  1702. bitmap = img.ConvertToBitmap()
  1703. mask = wx.Mask(bitmap, wx.WHITE)
  1704. bitmap.SetMask(mask)
  1705. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask = True)
  1706. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  1707. if textDict['rotate']:
  1708. rot = float(textDict['rotate'])
  1709. else:
  1710. rot = 0
  1711. fontsize = textDict['fontsize'] * self.currScale
  1712. if textDict['background'] != 'none':
  1713. background = textDict['background']
  1714. else:
  1715. background = None
  1716. pdc.RemoveId(drawId)
  1717. pdc.SetId(drawId)
  1718. pdc.BeginDrawing()
  1719. # border is not redrawn when zoom changes, why?
  1720. ## if textDict['border'] != 'none' and not rot:
  1721. ## units = UnitConversion(self)
  1722. ## borderWidth = units.convert(value = textDict['width'],
  1723. ## fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  1724. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  1725. ## pdc.DrawRectangle(*bounds)
  1726. if background:
  1727. pdc.SetTextBackground(convertRGB(background))
  1728. pdc.SetBackgroundMode(wx.SOLID)
  1729. else:
  1730. pdc.SetBackgroundMode(wx.TRANSPARENT)
  1731. fn = self.parent.makePSFont(textDict)
  1732. pdc.SetFont(fn)
  1733. pdc.SetTextForeground(convertRGB(textDict['color']))
  1734. pdc.DrawRotatedText(textDict['text'], coords[0], coords[1], rot)
  1735. pdc.SetIdBounds(drawId, wx.Rect(*bounds))
  1736. self.Refresh()
  1737. pdc.EndDrawing()
  1738. def DrawImage(self, rect):
  1739. """!Draw preview image to pseudoDC"""
  1740. self.pdcImage.ClearId(self.imageId)
  1741. self.pdcImage.SetId(self.imageId)
  1742. img = self.image
  1743. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  1744. img = img.Scale(rect.width, rect.height)
  1745. bitmap = img.ConvertToBitmap()
  1746. self.pdcImage.BeginDrawing()
  1747. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  1748. self.pdcImage.SetIdBounds(self.imageId, rect)
  1749. self.pdcImage.EndDrawing()
  1750. self.Refresh()
  1751. def DrawPaper(self, rect):
  1752. """!Draw paper and margins"""
  1753. page = self.instruction[self.pageId]
  1754. scale = page['Width'] / rect.GetWidth()
  1755. w = (page['Width'] - page['Right'] - page['Left']) / scale
  1756. h = (page['Height'] - page['Top'] - page['Bottom']) / scale
  1757. x = page['Left'] / scale + rect.GetX()
  1758. y = page['Top'] / scale + rect.GetY()
  1759. self.pdcPaper.BeginDrawing()
  1760. self.pdcPaper.RemoveId(self.pageId)
  1761. self.pdcPaper.SetId(self.pageId)
  1762. self.pdcPaper.SetPen(self.pen['paper'])
  1763. self.pdcPaper.SetBrush(self.brush['paper'])
  1764. self.pdcPaper.DrawRectangleRect(rect)
  1765. self.pdcPaper.SetPen(self.pen['margins'])
  1766. self.pdcPaper.SetBrush(self.brush['margins'])
  1767. self.pdcPaper.DrawRectangle(x, y, w, h)
  1768. self.pdcPaper.SetIdBounds(self.pageId, rect)
  1769. self.pdcPaper.EndDrawing()
  1770. self.Refresh()
  1771. def ImageRect(self):
  1772. """!Returns image centered in canvas, computes scale"""
  1773. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  1774. cW, cH = self.GetClientSize()
  1775. iW, iH = img.GetWidth(), img.GetHeight()
  1776. self.currScale = min(float(cW)/iW, float(cH)/iH)
  1777. iW = iW * self.currScale
  1778. iH = iH * self.currScale
  1779. x = cW/2 - iW/2
  1780. y = cH/2 - iH/2
  1781. imageRect = wx.Rect(x, y, iW, iH)
  1782. return imageRect
  1783. def RedrawSelectBox(self, id):
  1784. """!Redraws select box when selected object changes its size"""
  1785. if self.dragId == id:
  1786. rect = self.pdcObj.GetIdBounds(id)
  1787. if self.instruction[id].type != 'line':
  1788. rect = rect.Inflate(3,3)
  1789. # draw select box around object
  1790. self.Draw(pen = self.pen['select'], brush = self.brush['select'], pdc = self.pdcTmp,
  1791. drawid = self.idBoxTmp, pdctype = 'rect', bb = rect)
  1792. # draw small marks signalizing resizing
  1793. if self.instruction[id].type in ('map', 'rectangle'):
  1794. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  1795. rect = wx.RectPS(controlP, self.resizeBoxSize)
  1796. self.Draw(pen = self.pen['resize'], brush = self.brush['resize'], pdc = self.pdcTmp,
  1797. drawid = self.idResizeBoxTmp, pdctype = 'rect', bb = rect)
  1798. elif self.instruction[id].type == 'line':
  1799. p1Paper = self.instruction[id]['where'][0]
  1800. p2Paper = self.instruction[id]['where'][1]
  1801. p1Canvas = self.CanvasPaperCoordinates(rect = Rect2DPS(p1Paper, (0, 0)), canvasToPaper = False)[:2]
  1802. p2Canvas = self.CanvasPaperCoordinates(rect = Rect2DPS(p2Paper, (0, 0)), canvasToPaper = False)[:2]
  1803. rect = []
  1804. box = wx.RectS(self.resizeBoxSize)
  1805. rect.append(box.CenterIn(wx.RectPS(p1Canvas, wx.Size())))
  1806. rect.append(box.CenterIn(wx.RectPS(p2Canvas, wx.Size())))
  1807. for i, point in enumerate((p1Canvas, p2Canvas)):
  1808. self.Draw(pen = self.pen['resize'], brush = self.brush['resize'], pdc = self.pdcTmp,
  1809. drawid = self.idLinePointsTmp[i], pdctype = 'rect', bb = rect[i])
  1810. def UpdateMapLabel(self):
  1811. """!Updates map frame label"""
  1812. vector = self.instruction.FindInstructionByType('vector')
  1813. if vector:
  1814. vectorId = vector.id
  1815. else:
  1816. vectorId = None
  1817. raster = self.instruction.FindInstructionByType('raster')
  1818. if raster:
  1819. rasterId = raster.id
  1820. else:
  1821. rasterId = None
  1822. rasterName = 'None'
  1823. if rasterId:
  1824. rasterName = self.instruction[rasterId]['raster'].split('@')[0]
  1825. mapId = self.instruction.FindInstructionByType('map').id
  1826. self.itemLabels[mapId] = []
  1827. self.itemLabels[mapId].append(self.itemLabelsDict['map'])
  1828. self.itemLabels[mapId].append("raster: " + rasterName)
  1829. if vectorId:
  1830. for map in self.instruction[vectorId]['list']:
  1831. self.itemLabels[mapId].append('vector: ' + map[0].split('@')[0])
  1832. labels = self.instruction.FindInstructionByType('labels')
  1833. if labels:
  1834. labelFiles = self.instruction[labels.id]['labels']
  1835. if not labelFiles:
  1836. return
  1837. labelFiles = [lFile.split('@')[0] for lFile in labelFiles]
  1838. self.itemLabels[mapId].append(_("labels: ") + ', '.join(labelFiles))
  1839. def UpdateLabel(self, itype, id):
  1840. self.itemLabels[id] = []
  1841. self.itemLabels[id].append(self.itemLabelsDict[itype])
  1842. if itype == 'image':
  1843. file = os.path.basename(self.instruction[id]['epsfile'])
  1844. self.itemLabels[id].append(file)
  1845. def OnSize(self, event):
  1846. """!Init image size to match window size
  1847. """
  1848. # not zoom all when notebook page is changed
  1849. if self.preview and self.parent.currentPage == 1 or not self.preview and self.parent.currentPage == 0:
  1850. self.ZoomAll()
  1851. self.OnIdle(None)
  1852. event.Skip()
  1853. def OnIdle(self, event):
  1854. """!Only re-render a image during idle time instead of
  1855. multiple times during resizing.
  1856. """
  1857. width, height = self.GetClientSize()
  1858. # Make new off screen bitmap: this bitmap will always have the
  1859. # current drawing in it, so it can be used to save the image
  1860. # to a file, or whatever.
  1861. self._buffer = wx.EmptyBitmap(width, height)
  1862. # re-render image on idle
  1863. self.resize = True
  1864. def ScaleRect(self, rect, scale):
  1865. """! Scale rectangle"""
  1866. return wx.Rect(rect.GetLeft()*scale, rect.GetTop()*scale,
  1867. rect.GetSize()[0]*scale, rect.GetSize()[1]*scale)
  1868. # hack for Windows, loading EPS works only on Unix
  1869. # these functions are taken from EpsImagePlugin.py
  1870. def loadPSForWindows(self):
  1871. # Load EPS via Ghostscript
  1872. if not self.tile:
  1873. return
  1874. self.im = GhostscriptForWindows(self.tile, self.size, self.fp)
  1875. self.mode = self.im.mode
  1876. self.size = self.im.size
  1877. self.tile = []
  1878. def GhostscriptForWindows(tile, size, fp):
  1879. """Render an image using Ghostscript (Windows only)"""
  1880. # Unpack decoder tile
  1881. decoder, tile, offset, data = tile[0]
  1882. length, bbox = data
  1883. import tempfile, os
  1884. file = tempfile.mkstemp()[1]
  1885. # Build ghostscript command - for Windows
  1886. command = ["gswin32c",
  1887. "-q", # quite mode
  1888. "-g%dx%d" % size, # set output geometry (pixels)
  1889. "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode
  1890. "-sDEVICE=ppmraw", # ppm driver
  1891. "-sOutputFile=%s" % file # output file
  1892. ]
  1893. command = string.join(command)
  1894. # push data through ghostscript
  1895. try:
  1896. gs = os.popen(command, "w")
  1897. # adjust for image origin
  1898. if bbox[0] != 0 or bbox[1] != 0:
  1899. gs.write("%d %d translate\n" % (-bbox[0], -bbox[1]))
  1900. fp.seek(offset)
  1901. while length > 0:
  1902. s = fp.read(8192)
  1903. if not s:
  1904. break
  1905. length = length - len(s)
  1906. gs.write(s)
  1907. status = gs.close()
  1908. if status:
  1909. raise IOError("gs failed (status %d)" % status)
  1910. im = PILImage.core.open_ppm(file)
  1911. finally:
  1912. try: os.unlink(file)
  1913. except: pass
  1914. return im