frame.py 94 KB

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