frame.py 96 KB

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