frame.py 99 KB

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