frame.py 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724
  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 = 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. return Rect2D(X, Y, Width, Height)
  1280. def SetPage(self):
  1281. """Sets and changes page, redraws paper"""
  1282. page = self.instruction[self.pageId]
  1283. if not page:
  1284. page = PageSetup(id=self.pageId, env=self.env)
  1285. self.instruction.AddInstruction(page)
  1286. ppi = wx.ClientDC(self).GetPPI()
  1287. cW, cH = self.GetClientSize()
  1288. pW, pH = page["Width"] * ppi[0], page["Height"] * ppi[1]
  1289. if self.currScale is None:
  1290. self.currScale = min(cW / pW, cH / pH)
  1291. pW = pW * self.currScale
  1292. pH = pH * self.currScale
  1293. x = cW / 2 - pW / 2
  1294. y = cH / 2 - pH / 2
  1295. self.DrawPaper(Rect(x, y, pW, pH))
  1296. def modifyRectangle(self, r):
  1297. """Recalculates rectangle not to have negative size"""
  1298. if r.GetWidth() < 0:
  1299. r.SetX(r.GetX() + r.GetWidth())
  1300. if r.GetHeight() < 0:
  1301. r.SetY(r.GetY() + r.GetHeight())
  1302. r.SetWidth(abs(r.GetWidth()))
  1303. r.SetHeight(abs(r.GetHeight()))
  1304. return r
  1305. def RecalculateEN(self):
  1306. """Recalculate east and north for texts (eps, points) after their or map's movement"""
  1307. try:
  1308. mapId = self.instruction.FindInstructionByType("map").id
  1309. except AttributeError:
  1310. mapId = self.instruction.FindInstructionByType("initMap").id
  1311. for itemType in ("text", "image", "northArrow", "point", "line", "rectangle"):
  1312. items = self.instruction.FindInstructionByType(itemType, list=True)
  1313. for item in items:
  1314. instr = self.instruction[item.id]
  1315. if itemType in ("line", "rectangle"):
  1316. if itemType == "line":
  1317. e1, n1 = PaperMapCoordinates(
  1318. mapInstr=self.instruction[mapId],
  1319. x=instr["where"][0][0],
  1320. y=instr["where"][0][1],
  1321. paperToMap=True,
  1322. env=self.env,
  1323. )
  1324. e2, n2 = PaperMapCoordinates(
  1325. mapInstr=self.instruction[mapId],
  1326. x=instr["where"][1][0],
  1327. y=instr["where"][1][1],
  1328. paperToMap=True,
  1329. env=self.env,
  1330. )
  1331. else:
  1332. e1, n1 = PaperMapCoordinates(
  1333. mapInstr=self.instruction[mapId],
  1334. x=instr["rect"].GetLeft(),
  1335. y=instr["rect"].GetTop(),
  1336. paperToMap=True,
  1337. env=self.env,
  1338. )
  1339. e2, n2 = PaperMapCoordinates(
  1340. mapInstr=self.instruction[mapId],
  1341. x=instr["rect"].GetRight(),
  1342. y=instr["rect"].GetBottom(),
  1343. paperToMap=True,
  1344. env=self.env,
  1345. )
  1346. instr["east1"] = e1
  1347. instr["north1"] = n1
  1348. instr["east2"] = e2
  1349. instr["north2"] = n2
  1350. else:
  1351. e, n = PaperMapCoordinates(
  1352. mapInstr=self.instruction[mapId],
  1353. x=instr["where"][0],
  1354. y=instr["where"][1],
  1355. paperToMap=True,
  1356. env=self.env,
  1357. )
  1358. instr["east"], instr["north"] = e, n
  1359. def OnPaint(self, event):
  1360. """Draw pseudo DC to buffer"""
  1361. if not self._buffer:
  1362. return
  1363. dc = wx.BufferedPaintDC(self, self._buffer)
  1364. # use PrepareDC to set position correctly
  1365. # probably does nothing, removed from wxPython 2.9
  1366. # self.PrepareDC(dc)
  1367. dc.SetBackground(wx.LIGHT_GREY_BRUSH)
  1368. dc.Clear()
  1369. # draw paper
  1370. if not self.preview:
  1371. self.pdcPaper.DrawToDC(dc)
  1372. # draw to the DC using the calculated clipping rect
  1373. rgn = self.GetUpdateRegion()
  1374. if not self.preview:
  1375. self.pdcObj.DrawToDCClipped(dc, rgn.GetBox())
  1376. else:
  1377. self.pdcImage.DrawToDCClipped(dc, rgn.GetBox())
  1378. self.pdcTmp.DrawToDCClipped(dc, rgn.GetBox())
  1379. def MouseActions(self, event):
  1380. """Mouse motion and button click notifier"""
  1381. disable = self.preview and self.mouse["use"] in (
  1382. "pointer",
  1383. "resize",
  1384. "addMap",
  1385. "addPoint",
  1386. "addLine",
  1387. "addRectangle",
  1388. )
  1389. # zoom with mouse wheel
  1390. if event.GetWheelRotation() != 0:
  1391. self.OnMouseWheel(event)
  1392. # left mouse button pressed
  1393. elif event.LeftDown() and not disable:
  1394. self.OnLeftDown(event)
  1395. # left mouse button released
  1396. elif event.LeftUp() and not disable:
  1397. self.OnLeftUp(event)
  1398. # dragging
  1399. elif event.Dragging() and not disable:
  1400. self.OnDragging(event)
  1401. # double click
  1402. elif event.ButtonDClick() and not disable:
  1403. self.OnButtonDClick(event)
  1404. # middle mouse button pressed
  1405. elif event.MiddleDown():
  1406. self.OnMiddleDown(event)
  1407. elif event.Moving():
  1408. self.OnMouseMoving(event)
  1409. def OnMouseWheel(self, event):
  1410. """Mouse wheel scrolled.
  1411. Changes zoom."""
  1412. if (
  1413. UserSettings.Get(group="display", key="mouseWheelZoom", subkey="selection")
  1414. == 2
  1415. ):
  1416. event.Skip()
  1417. return
  1418. zoom = event.GetWheelRotation()
  1419. oldUse = self.mouse["use"]
  1420. self.mouse["begin"] = event.GetPosition()
  1421. if UserSettings.Get(group="display", key="scrollDirection", subkey="selection"):
  1422. zoom *= -1
  1423. if zoom > 0:
  1424. self.mouse["use"] = "zoomin"
  1425. else:
  1426. self.mouse["use"] = "zoomout"
  1427. zoomFactor, view = self.ComputeZoom(Rect(0, 0, 0, 0))
  1428. self.Zoom(zoomFactor, view)
  1429. self.mouse["use"] = oldUse
  1430. def OnMouseMoving(self, event):
  1431. """Mouse cursor moving.
  1432. Change cursor when moving over resize marker.
  1433. """
  1434. if self.preview:
  1435. return
  1436. if self.mouse["use"] in ("pointer", "resize"):
  1437. pos = event.GetPosition()
  1438. foundResize = self.pdcTmp.FindObjects(pos[0], pos[1])
  1439. if (
  1440. foundResize
  1441. and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp
  1442. ):
  1443. self.SetCursor(self.cursors["sizenwse"])
  1444. self.parent.SetStatusText(_("Click and drag to resize object"), 0)
  1445. self.showResizeHelp = True
  1446. else:
  1447. if self.showResizeHelp:
  1448. self.parent.SetStatusText("", 0)
  1449. self.SetCursor(self.cursors["default"])
  1450. self.showResizeHelp = False
  1451. def OnLeftDown(self, event):
  1452. """Left mouse button pressed.
  1453. Select objects, redraw, prepare for moving/resizing.
  1454. """
  1455. self.mouse["begin"] = event.GetPosition()
  1456. self.begin = self.mouse["begin"]
  1457. # select
  1458. if self.mouse["use"] == "pointer":
  1459. found = self.pdcObj.FindObjects(
  1460. self.mouse["begin"][0], self.mouse["begin"][1]
  1461. )
  1462. foundResize = self.pdcTmp.FindObjects(
  1463. self.mouse["begin"][0], self.mouse["begin"][1]
  1464. )
  1465. if (
  1466. foundResize
  1467. and foundResize[0] in (self.idResizeBoxTmp,) + self.idLinePointsTmp
  1468. ):
  1469. self.mouse["use"] = "resize"
  1470. # when resizing, proportions match region
  1471. if self.instruction[self.dragId].type == "map":
  1472. self.constraint = False
  1473. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1474. if self.instruction[self.dragId]["scaleType"] in (0, 1, 2):
  1475. self.constraint = True
  1476. self.mapBounds = self.pdcObj.GetIdBounds(self.dragId)
  1477. if self.instruction[self.dragId].type == "line":
  1478. self.currentLinePoint = self.idLinePointsTmp.index(foundResize[0])
  1479. elif found:
  1480. self.dragId = found[0]
  1481. self.RedrawSelectBox(self.dragId)
  1482. if self.instruction[self.dragId].type not in ("map", "rectangle"):
  1483. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1484. self.Refresh()
  1485. if self.instruction[self.dragId].type != "line":
  1486. for id in self.idLinePointsTmp:
  1487. self.pdcTmp.RemoveId(id)
  1488. self.Refresh()
  1489. else:
  1490. self.dragId = -1
  1491. self.pdcTmp.RemoveId(self.idBoxTmp)
  1492. self.pdcTmp.RemoveId(self.idResizeBoxTmp)
  1493. for id in self.idLinePointsTmp:
  1494. self.pdcTmp.RemoveId(id)
  1495. self.Refresh()
  1496. def OnLeftUp(self, event):
  1497. """Left mouse button released.
  1498. Recalculate zooming/resizing/moving and redraw.
  1499. """
  1500. # zoom in, zoom out
  1501. if self.mouse["use"] in ("zoomin", "zoomout"):
  1502. zoomR = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1503. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1504. self.Refresh()
  1505. zoomFactor, view = self.ComputeZoom(zoomR)
  1506. self.Zoom(zoomFactor, view)
  1507. # draw map frame
  1508. if self.mouse["use"] == "addMap":
  1509. rectTmp = self.pdcTmp.GetIdBounds(self.idZoomBoxTmp)
  1510. # too small rectangle, it's usually some mistake
  1511. if rectTmp.GetWidth() < 20 or rectTmp.GetHeight() < 20:
  1512. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1513. self.Refresh()
  1514. return
  1515. rectPaper = self.CanvasPaperCoordinates(rect=rectTmp, canvasToPaper=True)
  1516. dlg = MapDialog(
  1517. parent=self.parent,
  1518. id=[None, None, None],
  1519. settings=self.instruction,
  1520. env=self.env,
  1521. rect=rectPaper,
  1522. )
  1523. self.openDialogs["map"] = dlg
  1524. self.openDialogs["map"].Show()
  1525. self.parent.toolbar.SelectDefault()
  1526. return
  1527. # resize resizable objects (map, line, rectangle)
  1528. if self.mouse["use"] == "resize":
  1529. mapObj = self.instruction.FindInstructionByType("map")
  1530. if not mapObj:
  1531. mapObj = self.instruction.FindInstructionByType("initMap")
  1532. mapId = mapObj.id
  1533. if self.dragId == mapId:
  1534. # necessary to change either map frame (scaleType 0,1,2) or
  1535. # region (scaletype 3)
  1536. newRectCanvas = self.pdcObj.GetIdBounds(mapId)
  1537. newRectPaper = self.CanvasPaperCoordinates(
  1538. rect=newRectCanvas, canvasToPaper=True
  1539. )
  1540. self.instruction[mapId]["rect"] = newRectPaper
  1541. if self.instruction[mapId]["scaleType"] in (0, 1, 2):
  1542. if self.instruction[mapId]["scaleType"] == 0:
  1543. scale, foo, rect = AutoAdjust(
  1544. self,
  1545. scaleType=0,
  1546. map=self.instruction[mapId]["map"],
  1547. env=self.env,
  1548. mapType=self.instruction[mapId]["mapType"],
  1549. rect=self.instruction[mapId]["rect"],
  1550. )
  1551. elif self.instruction[mapId]["scaleType"] == 1:
  1552. scale, foo, rect = AutoAdjust(
  1553. self,
  1554. scaleType=1,
  1555. env=self.env,
  1556. region=self.instruction[mapId]["region"],
  1557. rect=self.instruction[mapId]["rect"],
  1558. )
  1559. else:
  1560. scale, foo, rect = AutoAdjust(
  1561. self,
  1562. scaleType=2,
  1563. rect=self.instruction[mapId]["rect"],
  1564. env=self.env,
  1565. )
  1566. self.instruction[mapId]["rect"] = rect
  1567. self.instruction[mapId]["scale"] = scale
  1568. rectCanvas = self.CanvasPaperCoordinates(
  1569. rect=rect, canvasToPaper=False
  1570. )
  1571. self.Draw(
  1572. pen=self.pen["map"],
  1573. brush=self.brush["map"],
  1574. pdc=self.pdcObj,
  1575. drawid=mapId,
  1576. pdctype="rectText",
  1577. bb=rectCanvas,
  1578. )
  1579. elif self.instruction[mapId]["scaleType"] == 3:
  1580. ComputeSetRegion(
  1581. self,
  1582. mapDict=self.instruction[mapId].GetInstruction(),
  1583. env=self.env,
  1584. )
  1585. # check resolution
  1586. SetResolution(
  1587. dpi=self.instruction[mapId]["resolution"],
  1588. width=self.instruction[mapId]["rect"].width,
  1589. height=self.instruction[mapId]["rect"].height,
  1590. env=self.env,
  1591. )
  1592. self.RedrawSelectBox(mapId)
  1593. self.Zoom(zoomFactor=1, view=(0, 0))
  1594. elif self.instruction[self.dragId].type == "line":
  1595. points = self.instruction[self.dragId]["where"]
  1596. self.instruction[self.dragId]["rect"] = Rect2DPP(points[0], points[1])
  1597. self.RecalculatePosition(ids=[self.dragId])
  1598. elif self.instruction[self.dragId].type == "rectangle":
  1599. self.RecalculatePosition(ids=[self.dragId])
  1600. self.mouse["use"] = "pointer"
  1601. # recalculate the position of objects after dragging
  1602. if self.mouse["use"] in ("pointer", "resize") and self.dragId != -1:
  1603. if self.mouse["begin"] != event.GetPosition(): # for double click
  1604. self.RecalculatePosition(ids=[self.dragId])
  1605. if self.instruction[self.dragId].type in self.openDialogs:
  1606. self.openDialogs[self.instruction[self.dragId].type].updateDialog()
  1607. elif self.mouse["use"] in ("addPoint", "addLine", "addRectangle"):
  1608. endCoordinates = self.CanvasPaperCoordinates(
  1609. rect=Rect(event.GetX(), event.GetY(), 0, 0), canvasToPaper=True
  1610. )[:2]
  1611. diffX = event.GetX() - self.mouse["begin"][0]
  1612. diffY = event.GetY() - self.mouse["begin"][1]
  1613. if self.mouse["use"] == "addPoint":
  1614. self.parent.AddPoint(coordinates=endCoordinates)
  1615. elif self.mouse["use"] in ("addLine", "addRectangle"):
  1616. # not too small lines/rectangles
  1617. if sqrt(diffX * diffX + diffY * diffY) < 5:
  1618. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1619. self.Refresh()
  1620. return
  1621. beginCoordinates = self.CanvasPaperCoordinates(
  1622. rect=Rect(self.mouse["begin"][0], self.mouse["begin"][1], 0, 0),
  1623. canvasToPaper=True,
  1624. )[:2]
  1625. if self.mouse["use"] == "addLine":
  1626. self.parent.AddLine(coordinates=[beginCoordinates, endCoordinates])
  1627. else:
  1628. self.parent.AddRectangle(
  1629. coordinates=[beginCoordinates, endCoordinates]
  1630. )
  1631. self.pdcTmp.RemoveId(self.idZoomBoxTmp)
  1632. self.Refresh()
  1633. def OnButtonDClick(self, event):
  1634. """Open object dialog for editing."""
  1635. if self.mouse["use"] == "pointer" and self.dragId != -1:
  1636. itemCall = {
  1637. "text": self.parent.OnAddText,
  1638. "mapinfo": self.parent.OnAddMapinfo,
  1639. "scalebar": self.parent.OnAddScalebar,
  1640. "image": self.parent.OnAddImage,
  1641. "northArrow": self.parent.OnAddNorthArrow,
  1642. "point": self.parent.AddPoint,
  1643. "line": self.parent.AddLine,
  1644. "rectangle": self.parent.AddRectangle,
  1645. "rasterLegend": self.parent.OnAddLegend,
  1646. "vectorLegend": self.parent.OnAddLegend,
  1647. "map": self.parent.OnAddMap,
  1648. }
  1649. itemArg = {
  1650. "text": dict(event=None, id=self.dragId),
  1651. "mapinfo": dict(event=None),
  1652. "scalebar": dict(event=None),
  1653. "image": dict(event=None, id=self.dragId),
  1654. "northArrow": dict(event=None, id=self.dragId),
  1655. "point": dict(id=self.dragId),
  1656. "line": dict(id=self.dragId),
  1657. "rectangle": dict(id=self.dragId),
  1658. "rasterLegend": dict(event=None),
  1659. "vectorLegend": dict(event=None, page=1),
  1660. "map": dict(event=None, notebook=True),
  1661. }
  1662. type = self.instruction[self.dragId].type
  1663. itemCall[type](**itemArg[type])
  1664. def OnDragging(self, event):
  1665. """Process panning/resizing/drawing/moving."""
  1666. if event.MiddleIsDown():
  1667. # panning
  1668. self.mouse["end"] = event.GetPosition()
  1669. self.Pan(begin=self.mouse["begin"], end=self.mouse["end"])
  1670. self.mouse["begin"] = event.GetPosition()
  1671. elif event.LeftIsDown():
  1672. # draw box when zooming, creating map
  1673. if self.mouse["use"] in (
  1674. "zoomin",
  1675. "zoomout",
  1676. "addMap",
  1677. "addLine",
  1678. "addRectangle",
  1679. ):
  1680. self.mouse["end"] = event.GetPosition()
  1681. r = Rect(
  1682. self.mouse["begin"][0],
  1683. self.mouse["begin"][1],
  1684. self.mouse["end"][0] - self.mouse["begin"][0],
  1685. self.mouse["end"][1] - self.mouse["begin"][1],
  1686. )
  1687. r = self.modifyRectangle(r)
  1688. if self.mouse["use"] in ("addLine", "addRectangle"):
  1689. if self.mouse["use"] == "addLine":
  1690. pdcType = "line"
  1691. lineCoords = (self.mouse["begin"], self.mouse["end"])
  1692. else:
  1693. pdcType = "rect"
  1694. lineCoords = None
  1695. if r[2] < 2 or r[3] < 2:
  1696. # to avoid strange behaviour
  1697. return
  1698. self.Draw(
  1699. pen=self.pen["line"],
  1700. brush=self.brush["line"],
  1701. pdc=self.pdcTmp,
  1702. drawid=self.idZoomBoxTmp,
  1703. pdctype=pdcType,
  1704. bb=r,
  1705. lineCoords=lineCoords,
  1706. )
  1707. else:
  1708. self.Draw(
  1709. pen=self.pen["box"],
  1710. brush=self.brush["box"],
  1711. pdc=self.pdcTmp,
  1712. drawid=self.idZoomBoxTmp,
  1713. pdctype="rect",
  1714. bb=r,
  1715. )
  1716. # panning
  1717. if self.mouse["use"] == "pan":
  1718. self.mouse["end"] = event.GetPosition()
  1719. self.Pan(begin=self.mouse["begin"], end=self.mouse["end"])
  1720. self.mouse["begin"] = event.GetPosition()
  1721. # move object
  1722. if self.mouse["use"] == "pointer" and self.dragId != -1:
  1723. self.mouse["end"] = event.GetPosition()
  1724. dx, dy = (
  1725. self.mouse["end"][0] - self.begin[0],
  1726. self.mouse["end"][1] - self.begin[1],
  1727. )
  1728. self.pdcObj.TranslateId(self.dragId, dx, dy)
  1729. self.pdcTmp.TranslateId(self.idBoxTmp, dx, dy)
  1730. self.pdcTmp.TranslateId(self.idResizeBoxTmp, dx, dy)
  1731. for id in self.idLinePointsTmp:
  1732. self.pdcTmp.TranslateId(id, dx, dy)
  1733. if self.instruction[self.dragId].type == "text":
  1734. self.instruction[self.dragId]["coords"] = (
  1735. self.instruction[self.dragId]["coords"][0] + dx,
  1736. self.instruction[self.dragId]["coords"][1] + dy,
  1737. )
  1738. self.begin = event.GetPosition()
  1739. self.Refresh()
  1740. # resize object
  1741. if self.mouse["use"] == "resize":
  1742. pos = event.GetPosition()
  1743. diffX = pos[0] - self.mouse["begin"][0]
  1744. diffY = pos[1] - self.mouse["begin"][1]
  1745. if self.instruction[self.dragId].type == "map":
  1746. x, y = self.mapBounds.GetX(), self.mapBounds.GetY()
  1747. width, height = (
  1748. self.mapBounds.GetWidth(),
  1749. self.mapBounds.GetHeight(),
  1750. )
  1751. # match given region
  1752. if self.constraint:
  1753. if width > height:
  1754. newWidth = width + diffX
  1755. newHeight = height + diffX * (float(height) / width)
  1756. else:
  1757. newWidth = width + diffY * (float(width) / height)
  1758. newHeight = height + diffY
  1759. else:
  1760. newWidth = width + diffX
  1761. newHeight = height + diffY
  1762. if newWidth < 10 or newHeight < 10:
  1763. return
  1764. bounds = Rect(x, y, newWidth, newHeight)
  1765. self.Draw(
  1766. pen=self.pen["map"],
  1767. brush=self.brush["map"],
  1768. pdc=self.pdcObj,
  1769. drawid=self.dragId,
  1770. pdctype="rectText",
  1771. bb=bounds,
  1772. )
  1773. elif self.instruction[self.dragId].type == "rectangle":
  1774. instr = self.instruction[self.dragId]
  1775. rect = self.CanvasPaperCoordinates(
  1776. rect=instr["rect"], canvasToPaper=False
  1777. )
  1778. rect.SetWidth(rect.GetWidth() + diffX)
  1779. rect.SetHeight(rect.GetHeight() + diffY)
  1780. if rect.GetWidth() < 5 or rect.GetHeight() < 5:
  1781. return
  1782. self.DrawGraphics(
  1783. drawid=self.dragId,
  1784. shape="rectangle",
  1785. color=instr["color"],
  1786. fcolor=instr["fcolor"],
  1787. width=instr["width"],
  1788. bb=rect,
  1789. )
  1790. elif self.instruction[self.dragId].type == "line":
  1791. instr = self.instruction[self.dragId]
  1792. points = instr["where"]
  1793. # moving point
  1794. if self.currentLinePoint == 0:
  1795. pPaper = points[1]
  1796. else:
  1797. pPaper = points[0]
  1798. pCanvas = self.CanvasPaperCoordinates(
  1799. rect=Rect2DPS(pPaper, (0, 0)), canvasToPaper=False
  1800. )[:2]
  1801. bounds = wx.Rect(pCanvas, pos)
  1802. self.DrawGraphics(
  1803. drawid=self.dragId,
  1804. shape="line",
  1805. color=instr["color"],
  1806. width=instr["width"],
  1807. bb=bounds,
  1808. lineCoords=(pos, pCanvas),
  1809. )
  1810. # update paper coordinates
  1811. points[self.currentLinePoint] = self.CanvasPaperCoordinates(
  1812. rect=Rect(pos[0], pos[1], 0, 0), canvasToPaper=True
  1813. )[:2]
  1814. self.RedrawSelectBox(self.dragId)
  1815. def OnMiddleDown(self, event):
  1816. """Middle mouse button pressed."""
  1817. self.mouse["begin"] = event.GetPosition()
  1818. def Pan(self, begin, end):
  1819. """Move canvas while dragging.
  1820. :param begin: x,y coordinates of first point
  1821. :param end: x,y coordinates of second point
  1822. """
  1823. view = begin[0] - end[0], begin[1] - end[1]
  1824. zoomFactor = 1
  1825. self.Zoom(zoomFactor, view)
  1826. def RecalculatePosition(self, ids):
  1827. for id in ids:
  1828. itype = self.instruction[id].type
  1829. if itype in ("map", "rectangle"):
  1830. self.instruction[id]["rect"] = self.CanvasPaperCoordinates(
  1831. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True
  1832. )
  1833. self.RecalculateEN()
  1834. elif itype in (
  1835. "mapinfo",
  1836. "rasterLegend",
  1837. "vectorLegend",
  1838. "image",
  1839. "northArrow",
  1840. ):
  1841. self.instruction[id]["rect"] = self.CanvasPaperCoordinates(
  1842. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True
  1843. )
  1844. self.instruction[id]["where"] = self.CanvasPaperCoordinates(
  1845. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True
  1846. )[:2]
  1847. if itype in ("image", "northArrow"):
  1848. self.RecalculateEN()
  1849. elif itype == "point":
  1850. rect = self.pdcObj.GetIdBounds(id)
  1851. self.instruction[id]["rect"] = self.CanvasPaperCoordinates(
  1852. rect=rect, canvasToPaper=True
  1853. )
  1854. rect.Offset(
  1855. dx=rect.GetWidth() / 2,
  1856. dy=rect.GetHeight() / 2,
  1857. )
  1858. self.instruction[id]["where"] = self.CanvasPaperCoordinates(
  1859. rect=rect, canvasToPaper=True
  1860. )[:2]
  1861. self.RecalculateEN()
  1862. elif itype == "line":
  1863. rect = self.pdcObj.GetIdBounds(id)
  1864. oldRect = self.instruction[id]["rect"]
  1865. newRect = self.CanvasPaperCoordinates(rect=rect, canvasToPaper=True)
  1866. xDiff = newRect[0] - oldRect[0]
  1867. yDiff = newRect[1] - oldRect[1]
  1868. self.instruction[id]["rect"] = newRect
  1869. point1 = wx.Point2D(*self.instruction[id]["where"][0])
  1870. point2 = wx.Point2D(*self.instruction[id]["where"][1])
  1871. point1 += wx.Point2D(xDiff, yDiff)
  1872. point2 += wx.Point2D(xDiff, yDiff)
  1873. self.instruction[id]["where"] = [point1, point2]
  1874. self.RecalculateEN()
  1875. elif itype == "scalebar":
  1876. self.instruction[id]["rect"] = self.CanvasPaperCoordinates(
  1877. rect=self.pdcObj.GetIdBounds(id), canvasToPaper=True
  1878. )
  1879. self.instruction[id]["where"] = self.instruction[id]["rect"].GetCentre()
  1880. elif itype == "text":
  1881. x, y = (
  1882. self.instruction[id]["coords"][0] - self.instruction[id]["xoffset"],
  1883. self.instruction[id]["coords"][1] + self.instruction[id]["yoffset"],
  1884. )
  1885. extent = self.parent.getTextExtent(textDict=self.instruction[id])
  1886. if self.instruction[id]["rotate"] is not None:
  1887. rot = float(self.instruction[id]["rotate"]) / 180 * pi
  1888. else:
  1889. rot = 0
  1890. if self.instruction[id]["ref"].split()[0] == "lower":
  1891. y += extent[1]
  1892. elif self.instruction[id]["ref"].split()[0] == "center":
  1893. y += extent[1] / 2
  1894. if self.instruction[id]["ref"].split()[1] == "right":
  1895. x += extent[0] * cos(rot)
  1896. y -= extent[0] * sin(rot)
  1897. elif self.instruction[id]["ref"].split()[1] == "center":
  1898. x += extent[0] / 2 * cos(rot)
  1899. y -= extent[0] / 2 * sin(rot)
  1900. self.instruction[id]["where"] = self.CanvasPaperCoordinates(
  1901. rect=Rect2D(x, y, 0, 0), canvasToPaper=True
  1902. )[:2]
  1903. self.RecalculateEN()
  1904. def ComputeZoom(self, rect):
  1905. """Computes zoom factor and scroll view"""
  1906. zoomFactor = 1
  1907. cW, cH = self.GetClientSize()
  1908. cW = float(cW)
  1909. if rect.IsEmpty(): # clicked on canvas
  1910. zoomFactor = 1.5
  1911. if self.mouse["use"] == "zoomout":
  1912. zoomFactor = 1.0 / zoomFactor
  1913. x, y = self.mouse["begin"]
  1914. xView = x - x / zoomFactor # x - cW/(zoomFactor * 2)
  1915. yView = y - y / zoomFactor # y - cH/(zoomFactor * 2)
  1916. else: # dragging
  1917. rW, rH = float(rect.GetWidth()), float(rect.GetHeight())
  1918. try:
  1919. zoomFactor = 1 / max(rW / cW, rH / cH)
  1920. except ZeroDivisionError:
  1921. zoomFactor = 1
  1922. # when zooming to full extent, in some cases, there was zoom
  1923. # 1.01..., which causes problem
  1924. if abs(zoomFactor - 1) > 0.01:
  1925. zoomFactor = zoomFactor
  1926. else:
  1927. zoomFactor = 1.0
  1928. if self.mouse["use"] == "zoomout":
  1929. zoomFactor = min(rW / cW, rH / cH)
  1930. try:
  1931. if rW / rH > cW / cH:
  1932. yView = rect.GetY() - (rW * (cH / cW) - rH) / 2
  1933. xView = rect.GetX()
  1934. if self.mouse["use"] == "zoomout":
  1935. x, y = rect.GetX() + (rW - (cW / cH) * rH) / 2, rect.GetY()
  1936. xView, yView = -x, -y
  1937. else:
  1938. xView = rect.GetX() - (rH * (cW / cH) - rW) / 2
  1939. yView = rect.GetY()
  1940. if self.mouse["use"] == "zoomout":
  1941. x, y = rect.GetX(), rect.GetY() + (rH - (cH / cW) * rW) / 2
  1942. xView, yView = -x, -y
  1943. except ZeroDivisionError:
  1944. xView, yView = rect.GetX(), rect.GetY()
  1945. return zoomFactor, (int(xView), int(yView))
  1946. def Zoom(self, zoomFactor, view):
  1947. """Zoom to specified region, scroll view, redraw"""
  1948. if not self.currScale:
  1949. return
  1950. self.currScale = self.currScale * zoomFactor
  1951. if self.currScale > 10 or self.currScale < 0.1:
  1952. self.currScale = self.currScale / zoomFactor
  1953. return
  1954. if not self.preview:
  1955. # redraw paper
  1956. pRect = self.pdcPaper.GetIdBounds(self.pageId)
  1957. if globalvar.wxPythonPhoenix:
  1958. pRect.Offset(-view[0], -view[1])
  1959. else:
  1960. pRect.OffsetXY(-view[0], -view[1])
  1961. pRect = self.ScaleRect(rect=pRect, scale=zoomFactor)
  1962. self.DrawPaper(pRect)
  1963. # redraw objects
  1964. for id in self.objectId:
  1965. type = self.instruction[id].type
  1966. if type == "labels": # why it's here? it should not
  1967. continue
  1968. oRect = self.CanvasPaperCoordinates(
  1969. rect=self.instruction[id]["rect"], canvasToPaper=False
  1970. )
  1971. if type == "text":
  1972. # recalculate coordinates, they are not equal to BB
  1973. coords = self.instruction[id]["coords"]
  1974. self.instruction[id]["coords"] = coords = [
  1975. (int(coord) - view[i]) * zoomFactor
  1976. for i, coord in enumerate(coords)
  1977. ]
  1978. extent = self.parent.getTextExtent(textDict=self.instruction[id])
  1979. if self.instruction[id]["rotate"]:
  1980. rot = float(self.instruction[id]["rotate"])
  1981. else:
  1982. rot = 0
  1983. self.instruction[id][
  1984. "rect"
  1985. ] = bounds = self.parent.getModifiedTextBounds(
  1986. coords[0], coords[1], extent, rot
  1987. )
  1988. self.DrawRotText(
  1989. pdc=self.pdcObj,
  1990. drawId=id,
  1991. textDict=self.instruction[id],
  1992. coords=coords,
  1993. bounds=bounds,
  1994. )
  1995. self.pdcObj.SetIdBounds(id, bounds)
  1996. elif type == "northArrow":
  1997. self.Draw(
  1998. pen=self.pen[type],
  1999. brush=self.brush[type],
  2000. pdc=self.pdcObj,
  2001. drawid=id,
  2002. pdctype="bitmap",
  2003. bb=oRect,
  2004. )
  2005. elif type in ("point", "line", "rectangle"):
  2006. instr = self.instruction[id]
  2007. color = self.instruction[id]["color"]
  2008. width = fcolor = coords = None
  2009. if type in ("point", "rectangle"):
  2010. fcolor = self.instruction[id]["fcolor"]
  2011. if type in ("line", "rectangle"):
  2012. width = self.instruction[id]["width"]
  2013. if type in ("line"):
  2014. point1, point2 = instr["where"][0], instr["where"][1]
  2015. point1 = self.CanvasPaperCoordinates(
  2016. rect=Rect2DPS(point1, (0, 0)), canvasToPaper=False
  2017. )[:2]
  2018. point2 = self.CanvasPaperCoordinates(
  2019. rect=Rect2DPS(point2, (0, 0)), canvasToPaper=False
  2020. )[:2]
  2021. coords = (point1, point2)
  2022. self.DrawGraphics(
  2023. drawid=id,
  2024. shape=type,
  2025. bb=oRect,
  2026. lineCoords=coords,
  2027. color=color,
  2028. fcolor=fcolor,
  2029. width=width,
  2030. )
  2031. else:
  2032. self.Draw(
  2033. pen=self.pen[type],
  2034. brush=self.brush[type],
  2035. pdc=self.pdcObj,
  2036. drawid=id,
  2037. pdctype="rectText",
  2038. bb=oRect,
  2039. )
  2040. # redraw tmp objects
  2041. if self.dragId != -1:
  2042. self.RedrawSelectBox(self.dragId)
  2043. # redraw preview
  2044. else: # preview mode
  2045. imageRect = self.pdcImage.GetIdBounds(self.imageId)
  2046. if globalvar.wxPythonPhoenix:
  2047. imageRect.Offset(-view[0], -view[1])
  2048. else:
  2049. imageRect.OffsetXY(-view[0], -view[1])
  2050. imageRect = self.ScaleRect(rect=imageRect, scale=zoomFactor)
  2051. self.DrawImage(imageRect)
  2052. def ZoomAll(self):
  2053. """Zoom to full extent"""
  2054. if not self.preview:
  2055. bounds = self.pdcPaper.GetIdBounds(self.pageId)
  2056. else:
  2057. bounds = self.pdcImage.GetIdBounds(self.imageId)
  2058. zoomP = bounds.Inflate(bounds.width / 20, bounds.height / 20)
  2059. zoomFactor, view = self.ComputeZoom(zoomP)
  2060. self.Zoom(zoomFactor, view)
  2061. def Draw(
  2062. self,
  2063. pen,
  2064. brush,
  2065. pdc,
  2066. drawid=None,
  2067. pdctype="rect",
  2068. bb=Rect(0, 0, 0, 0),
  2069. lineCoords=None,
  2070. ):
  2071. """Draw object with given pen and brush.
  2072. :param pdc: PseudoDC
  2073. :param pdctype: 'bitmap'/'rectText'/'rect'/'point'/'line'
  2074. :param bb: bounding box
  2075. :param lineCoords: coordinates of line start, end points (wx.Point, wx.Point)
  2076. """
  2077. if drawid is None:
  2078. drawid = NewId()
  2079. bb = bb.Get()
  2080. pdc.BeginDrawing()
  2081. pdc.RemoveId(drawid)
  2082. pdc.SetId(drawid)
  2083. pdc.SetPen(pen)
  2084. pdc.SetBrush(brush)
  2085. if pdctype == "bitmap":
  2086. if havePILImage:
  2087. file = self.instruction[drawid]["epsfile"]
  2088. rotation = self.instruction[drawid]["rotate"]
  2089. self.DrawBitmap(pdc=pdc, filePath=file, rotation=rotation, bbox=bb)
  2090. else: # draw only rectangle with label
  2091. pdctype = "rectText"
  2092. if pdctype in ("rect", "rectText"):
  2093. pdc.DrawRectangle(*bb)
  2094. if pdctype == "rectText":
  2095. # dc created because of method GetTextExtent, which pseudoDC lacks
  2096. dc = ClientDC(self)
  2097. font = dc.GetFont()
  2098. size = 10
  2099. font.SetPointSize(size)
  2100. font.SetStyle(wx.ITALIC)
  2101. dc.SetFont(font)
  2102. pdc.SetFont(font)
  2103. text = "\n".join(self.itemLabels[drawid])
  2104. w, h, lh = dc.GetFullMultiLineTextExtent(text)
  2105. textExtent = (w, h)
  2106. textRect = Rect(0, 0, *textExtent).CenterIn(bb)
  2107. r = map(int, bb)
  2108. while not Rect(*r).ContainsRect(textRect) and size >= 8:
  2109. size -= 2
  2110. font.SetPointSize(size)
  2111. dc.SetFont(font)
  2112. pdc.SetFont(font)
  2113. textExtent = dc.GetTextExtent(text)
  2114. textRect = Rect(0, 0, *textExtent).CenterIn(bb)
  2115. pdc.SetTextForeground(wx.Colour(100, 100, 100, 200))
  2116. pdc.SetBackgroundMode(wx.TRANSPARENT)
  2117. pdc.DrawLabel(text=text, rect=textRect)
  2118. elif pdctype == "point":
  2119. pdc.DrawCircle(x=bb[0] + bb[2] / 2, y=bb[1] + bb[3] / 2, radius=bb[2] / 2)
  2120. elif pdctype == "line":
  2121. pdc.DrawLinePoint(lineCoords[0], lineCoords[1])
  2122. pdc.SetIdBounds(drawid, bb)
  2123. pdc.EndDrawing()
  2124. self.Refresh()
  2125. return drawid
  2126. def DrawGraphics(
  2127. self, drawid, shape, color, bb, width=None, fcolor=None, lineCoords=None
  2128. ):
  2129. """Draw point/line/rectangle with given color and width
  2130. :param drawid: id of drawn object
  2131. :param shape: drawn shape 'point'/'line'/'rectangle'
  2132. :param color: pen outline color ('RRR:GGG:BBB')
  2133. :param fcolor: brush fill color, if meaningful ('RRR:GGG:BBB')
  2134. :param width: pen width
  2135. :param bb: bounding box
  2136. :param lineCoords: line coordinates (for line only)
  2137. """
  2138. pdctype = {"point": "point", "line": "line", "rectangle": "rect"}
  2139. if color == "none":
  2140. pen = wx.TRANSPARENT_PEN
  2141. else:
  2142. if width is not None:
  2143. units = UnitConversion(self)
  2144. width = int(
  2145. units.convert(value=width, fromUnit="point", toUnit="pixel")
  2146. * self.currScale
  2147. )
  2148. else:
  2149. width = 2
  2150. pen = wx.Pen(colour=convertRGB(color), width=width)
  2151. pen.SetCap(wx.CAP_BUTT) # this is how ps.map draws
  2152. brush = wx.TRANSPARENT_BRUSH
  2153. if fcolor and fcolor != "none":
  2154. brush = wx.Brush(colour=convertRGB(fcolor))
  2155. self.Draw(
  2156. pen=pen,
  2157. brush=brush,
  2158. pdc=self.pdcObj,
  2159. pdctype=pdctype[shape],
  2160. drawid=drawid,
  2161. bb=bb,
  2162. lineCoords=lineCoords,
  2163. )
  2164. def DrawBitmap(self, pdc, filePath, rotation, bbox):
  2165. """Draw bitmap using PIL"""
  2166. pImg = PILImage.open(filePath)
  2167. if sys.platform == "win32" and "eps" in os.path.splitext(filePath)[1].lower():
  2168. import types
  2169. pImg.load = types.MethodType(loadPSForWindows, pImg)
  2170. if rotation:
  2171. # get rid of black background
  2172. pImg = pImg.convert("RGBA")
  2173. rot = pImg.rotate(rotation, expand=1)
  2174. new = PILImage.new("RGBA", rot.size, (255,) * 4)
  2175. pImg = PILImage.composite(rot, new, rot)
  2176. pImg = pImg.resize((int(bbox[2]), int(bbox[3])), resample=PILImage.BICUBIC)
  2177. img = PilImageToWxImage(pImg)
  2178. bitmap = img.ConvertToBitmap()
  2179. mask = wx.Mask(bitmap, wx.WHITE)
  2180. bitmap.SetMask(mask)
  2181. pdc.DrawBitmap(bitmap, bbox[0], bbox[1], useMask=True)
  2182. def DrawRotText(self, pdc, drawId, textDict, coords, bounds):
  2183. if textDict["rotate"]:
  2184. rot = float(textDict["rotate"])
  2185. else:
  2186. rot = 0
  2187. if textDict["background"] != "none":
  2188. background = textDict["background"]
  2189. else:
  2190. background = None
  2191. pdc.RemoveId(drawId)
  2192. pdc.SetId(drawId)
  2193. pdc.BeginDrawing()
  2194. # border is not redrawn when zoom changes, why?
  2195. # if textDict['border'] != 'none' and not rot:
  2196. ## units = UnitConversion(self)
  2197. # borderWidth = units.convert(value = textDict['width'],
  2198. # fromUnit = 'point', toUnit = 'pixel' ) * self.currScale
  2199. ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth))
  2200. # pdc.DrawRectangle(*bounds)
  2201. if background:
  2202. pdc.SetTextBackground(convertRGB(background))
  2203. pdc.SetBackgroundMode(wx.SOLID)
  2204. else:
  2205. pdc.SetBackgroundMode(wx.TRANSPARENT)
  2206. fn = self.parent.makePSFont(textDict)
  2207. pdc.SetFont(fn)
  2208. pdc.SetTextForeground(convertRGB(textDict["color"]))
  2209. if rot == 0:
  2210. pdc.DrawLabel(text=textDict["text"], rect=bounds)
  2211. else:
  2212. pdc.DrawRotatedText(textDict["text"], coords[0], coords[1], rot)
  2213. pdc.SetIdBounds(drawId, Rect(*bounds))
  2214. self.Refresh()
  2215. pdc.EndDrawing()
  2216. def DrawImage(self, rect):
  2217. """Draw preview image to pseudoDC"""
  2218. self.pdcImage.ClearId(self.imageId)
  2219. self.pdcImage.SetId(self.imageId)
  2220. img = self.image
  2221. if img.GetWidth() != rect.width or img.GetHeight() != rect.height:
  2222. img = img.Scale(rect.width, rect.height)
  2223. bitmap = img.ConvertToBitmap()
  2224. self.pdcImage.BeginDrawing()
  2225. self.pdcImage.DrawBitmap(bitmap, rect.x, rect.y)
  2226. self.pdcImage.SetIdBounds(self.imageId, rect)
  2227. self.pdcImage.EndDrawing()
  2228. self.Refresh()
  2229. def DrawPaper(self, rect):
  2230. """Draw paper and margins"""
  2231. page = self.instruction[self.pageId]
  2232. scale = page["Width"] / rect.GetWidth()
  2233. w = (page["Width"] - page["Right"] - page["Left"]) / scale
  2234. h = (page["Height"] - page["Top"] - page["Bottom"]) / scale
  2235. x = page["Left"] / scale + rect.GetX()
  2236. y = page["Top"] / scale + rect.GetY()
  2237. self.pdcPaper.BeginDrawing()
  2238. self.pdcPaper.RemoveId(self.pageId)
  2239. self.pdcPaper.SetId(self.pageId)
  2240. self.pdcPaper.SetPen(self.pen["paper"])
  2241. self.pdcPaper.SetBrush(self.brush["paper"])
  2242. self.pdcPaper.DrawRectangleRect(rect)
  2243. self.pdcPaper.SetPen(self.pen["margins"])
  2244. self.pdcPaper.SetBrush(self.brush["margins"])
  2245. self.pdcPaper.DrawRectangle(x, y, w, h)
  2246. self.pdcPaper.SetIdBounds(self.pageId, rect)
  2247. self.pdcPaper.EndDrawing()
  2248. self.Refresh()
  2249. def ImageRect(self):
  2250. """Returns image centered in canvas, computes scale"""
  2251. img = wx.Image(self.imgName, wx.BITMAP_TYPE_PNG)
  2252. cW, cH = self.GetClientSize()
  2253. iW, iH = img.GetWidth(), img.GetHeight()
  2254. self.currScale = min(float(cW) / iW, float(cH) / iH)
  2255. iW = iW * self.currScale
  2256. iH = iH * self.currScale
  2257. x = cW / 2 - iW / 2
  2258. y = cH / 2 - iH / 2
  2259. imageRect = Rect(x, y, iW, iH)
  2260. return imageRect
  2261. def RedrawSelectBox(self, id):
  2262. """Redraws select box when selected object changes its size"""
  2263. if self.dragId == id:
  2264. rect = self.pdcObj.GetIdBounds(id)
  2265. if self.instruction[id].type != "line":
  2266. rect = rect.Inflate(3, 3)
  2267. # draw select box around object
  2268. self.Draw(
  2269. pen=self.pen["select"],
  2270. brush=self.brush["select"],
  2271. pdc=self.pdcTmp,
  2272. drawid=self.idBoxTmp,
  2273. pdctype="rect",
  2274. bb=rect,
  2275. )
  2276. # draw small marks signalizing resizing
  2277. if self.instruction[id].type in ("map", "rectangle"):
  2278. controlP = self.pdcObj.GetIdBounds(id).GetBottomRight()
  2279. rect = Rect(
  2280. controlP[0],
  2281. controlP[1],
  2282. self.resizeBoxSize[0],
  2283. self.resizeBoxSize[1],
  2284. )
  2285. self.Draw(
  2286. pen=self.pen["resize"],
  2287. brush=self.brush["resize"],
  2288. pdc=self.pdcTmp,
  2289. drawid=self.idResizeBoxTmp,
  2290. pdctype="rect",
  2291. bb=rect,
  2292. )
  2293. elif self.instruction[id].type == "line":
  2294. p1Paper = self.instruction[id]["where"][0]
  2295. p2Paper = self.instruction[id]["where"][1]
  2296. p1Canvas = self.CanvasPaperCoordinates(
  2297. rect=Rect2DPS(p1Paper, (0, 0)), canvasToPaper=False
  2298. )[:2]
  2299. p2Canvas = self.CanvasPaperCoordinates(
  2300. rect=Rect2DPS(p2Paper, (0, 0)), canvasToPaper=False
  2301. )[:2]
  2302. rect = []
  2303. box = Rect(0, 0, self.resizeBoxSize[0], self.resizeBoxSize[1])
  2304. rect.append(box.CenterIn(Rect(p1Canvas[0], p1Canvas[1], 0, 0)))
  2305. rect.append(box.CenterIn(Rect(p2Canvas[0], p2Canvas[1], 0, 0)))
  2306. for i, point in enumerate((p1Canvas, p2Canvas)):
  2307. self.Draw(
  2308. pen=self.pen["resize"],
  2309. brush=self.brush["resize"],
  2310. pdc=self.pdcTmp,
  2311. drawid=self.idLinePointsTmp[i],
  2312. pdctype="rect",
  2313. bb=rect[i],
  2314. )
  2315. def UpdateMapLabel(self):
  2316. """Updates map frame label"""
  2317. vector = self.instruction.FindInstructionByType("vector")
  2318. if vector:
  2319. vectorId = vector.id
  2320. else:
  2321. vectorId = None
  2322. raster = self.instruction.FindInstructionByType("raster")
  2323. if raster:
  2324. rasterId = raster.id
  2325. else:
  2326. rasterId = None
  2327. rasterName = "None"
  2328. if rasterId:
  2329. rasterName = self.instruction[rasterId]["raster"].split("@")[0]
  2330. mapId = self.instruction.FindInstructionByType("map").id
  2331. self.itemLabels[mapId] = []
  2332. self.itemLabels[mapId].append(self.itemLabelsDict["map"])
  2333. self.itemLabels[mapId].append("raster: " + rasterName)
  2334. if vectorId:
  2335. for map in self.instruction[vectorId]["list"]:
  2336. self.itemLabels[mapId].append("vector: " + map[0].split("@")[0])
  2337. labels = self.instruction.FindInstructionByType("labels")
  2338. if labels:
  2339. labelFiles = self.instruction[labels.id]["labels"]
  2340. if not labelFiles:
  2341. return
  2342. labelFiles = [lFile.split("@")[0] for lFile in labelFiles]
  2343. self.itemLabels[mapId].append(_("labels: ") + ", ".join(labelFiles))
  2344. def UpdateLabel(self, itype, id):
  2345. self.itemLabels[id] = []
  2346. self.itemLabels[id].append(self.itemLabelsDict[itype])
  2347. if itype == "image":
  2348. file = os.path.basename(self.instruction[id]["epsfile"])
  2349. self.itemLabels[id].append(file)
  2350. def OnSize(self, event):
  2351. """Init image size to match window size"""
  2352. # not zoom all when notebook page is changed
  2353. if (
  2354. self.preview
  2355. and self.parent.currentPage == 1
  2356. or not self.preview
  2357. and self.parent.currentPage == 0
  2358. ):
  2359. self.ZoomAll()
  2360. self.OnIdle(None)
  2361. event.Skip()
  2362. def OnIdle(self, event):
  2363. """Only re-render a image during idle time instead of
  2364. multiple times during resizing.
  2365. """
  2366. width, height = self.GetClientSize()
  2367. # Make new off screen bitmap: this bitmap will always have the
  2368. # current drawing in it, so it can be used to save the image
  2369. # to a file, or whatever.
  2370. width = max(width, 20)
  2371. height = max(height, 20)
  2372. self._buffer = EmptyBitmap(width, height)
  2373. # re-render image on idle
  2374. self.resize = True
  2375. def ScaleRect(self, rect, scale):
  2376. """Scale rectangle"""
  2377. return Rect(
  2378. rect.GetLeft() * scale,
  2379. rect.GetTop() * scale,
  2380. rect.GetSize()[0] * scale,
  2381. rect.GetSize()[1] * scale,
  2382. )