frame.py 95 KB

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