FlatCAM.py 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://caram.cl/software/flatcam #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import threading
  9. # TODO: Bundle together. This is just for debugging.
  10. from docutils.nodes import image
  11. from gi.repository import Gtk
  12. from gi.repository import Gdk
  13. from gi.repository import GdkPixbuf
  14. from gi.repository import GLib
  15. from gi.repository import GObject
  16. import simplejson as json
  17. import matplotlib
  18. from matplotlib.figure import Figure
  19. from numpy import arange, sin, pi
  20. from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
  21. #from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
  22. from camlib import *
  23. import sys
  24. import urllib
  25. import copy
  26. import random
  27. ########################################
  28. ## FlatCAMObj ##
  29. ########################################
  30. class FlatCAMObj:
  31. """
  32. Base type of objects handled in FlatCAM. These become interactive
  33. in the GUI, can be plotted, and their options can be modified
  34. by the user in their respective forms.
  35. """
  36. # Instance of the application to which these are related.
  37. # The app should set this value.
  38. app = None
  39. def __init__(self, name):
  40. self.options = {"name": name}
  41. self.form_kinds = {"name": "entry_text"} # Kind of form element for each option
  42. self.radios = {} # Name value pairs for radio sets
  43. self.radios_inv = {} # Inverse of self.radios
  44. self.axes = None # Matplotlib axes
  45. self.kind = None # Override with proper name
  46. def setup_axes(self, figure):
  47. """
  48. 1) Creates axes if they don't exist. 2) Clears axes. 3) Attaches
  49. them to figure if not part of the figure. 4) Sets transparent
  50. background. 5) Sets 1:1 scale aspect ratio.
  51. :param figure: A Matplotlib.Figure on which to add/configure axes.
  52. :type figure: matplotlib.figure.Figure
  53. :return: None
  54. :rtype: None
  55. """
  56. if self.axes is None:
  57. print "New axes"
  58. self.axes = figure.add_axes([0.05, 0.05, 0.9, 0.9],
  59. label=self.options["name"])
  60. elif self.axes not in figure.axes:
  61. print "Clearing and attaching axes"
  62. self.axes.cla()
  63. figure.add_axes(self.axes)
  64. else:
  65. print "Clearing Axes"
  66. self.axes.cla()
  67. # Remove all decoration. The app's axes will have
  68. # the ticks and grid.
  69. self.axes.set_frame_on(False) # No frame
  70. self.axes.set_xticks([]) # No tick
  71. self.axes.set_yticks([]) # No ticks
  72. self.axes.patch.set_visible(False) # No background
  73. self.axes.set_aspect(1)
  74. def to_form(self):
  75. """
  76. Copies options to the UI form.
  77. :return: None
  78. """
  79. for option in self.options:
  80. self.set_form_item(option)
  81. def read_form(self):
  82. """
  83. Reads form into ``self.options``.
  84. :return: None
  85. :rtype: None
  86. """
  87. for option in self.options:
  88. self.read_form_item(option)
  89. def build_ui(self):
  90. """
  91. Sets up the UI/form for this object.
  92. :return: None
  93. :rtype: None
  94. """
  95. # Where the UI for this object is drawn
  96. box_selected = self.app.builder.get_object("box_selected")
  97. # Remove anything else in the box
  98. box_children = box_selected.get_children()
  99. for child in box_children:
  100. box_selected.remove(child)
  101. osw = self.app.builder.get_object("offscrwindow_" + self.kind) # offscreenwindow
  102. sw = self.app.builder.get_object("sw_" + self.kind) # scrollwindows
  103. osw.remove(sw) # TODO: Is this needed ?
  104. vp = self.app.builder.get_object("vp_" + self.kind) # Viewport
  105. vp.override_background_color(Gtk.StateType.NORMAL, Gdk.RGBA(1, 1, 1, 1))
  106. # Put in the UI
  107. box_selected.pack_start(sw, True, True, 0)
  108. entry_name = self.app.builder.get_object("entry_text_" + self.kind + "_name")
  109. entry_name.connect("activate", self.app.on_activate_name)
  110. self.to_form()
  111. sw.show()
  112. def set_form_item(self, option):
  113. """
  114. Copies the specified option to the UI form.
  115. :param option: Name of the option (Key in ``self.options``).
  116. :type option: str
  117. :return: None
  118. """
  119. fkind = self.form_kinds[option]
  120. fname = fkind + "_" + self.kind + "_" + option
  121. if fkind == 'entry_eval' or fkind == 'entry_text':
  122. self.app.builder.get_object(fname).set_text(str(self.options[option]))
  123. return
  124. if fkind == 'cb':
  125. self.app.builder.get_object(fname).set_active(self.options[option])
  126. return
  127. if fkind == 'radio':
  128. self.app.builder.get_object(self.radios_inv[option][self.options[option]]).set_active(True)
  129. return
  130. print "Unknown kind of form item:", fkind
  131. def read_form_item(self, option):
  132. """
  133. Reads the specified option from the UI form into ``self.options``.
  134. :param option: Name of the option.
  135. :type option: str
  136. :return: None
  137. """
  138. fkind = self.form_kinds[option]
  139. fname = fkind + "_" + self.kind + "_" + option
  140. if fkind == 'entry_text':
  141. self.options[option] = self.app.builder.get_object(fname).get_text()
  142. return
  143. if fkind == 'entry_eval':
  144. self.options[option] = self.app.get_eval(fname)
  145. return
  146. if fkind == 'cb':
  147. self.options[option] = self.app.builder.get_object(fname).get_active()
  148. return
  149. if fkind == 'radio':
  150. self.options[option] = self.app.get_radio_value(self.radios[option])
  151. return
  152. print "Unknown kind of form item:", fkind
  153. def plot(self):
  154. """
  155. Plot this object (Extend this method to implement the actual plotting).
  156. Axes get created, appended to canvas and cleared before plotting.
  157. Call this in descendants before doing the plotting.
  158. :return: Whether to continue plotting or not depending on the "plot" option.
  159. :rtype: bool
  160. """
  161. # Axes must exist and be attached to canvas.
  162. if self.axes is None or self.axes not in self.app.plotcanvas.figure.axes:
  163. self.axes = self.app.plotcanvas.new_axes(self.options['name'])
  164. if not self.options["plot"]:
  165. self.axes.cla()
  166. self.app.plotcanvas.auto_adjust_axes()
  167. return False
  168. # Clear axes or we will plot on top of them.
  169. self.axes.cla()
  170. # GLib.idle_add(self.axes.cla)
  171. return True
  172. def serialize(self):
  173. """
  174. Returns a representation of the object as a dictionary so
  175. it can be later exported as JSON. Override this method.
  176. :return: Dictionary representing the object
  177. :rtype: dict
  178. """
  179. return
  180. def deserialize(self, obj_dict):
  181. """
  182. Re-builds an object from its serialized version.
  183. :param obj_dict: Dictionary representing a FlatCAMObj
  184. :type obj_dict: dict
  185. :return: None
  186. """
  187. return
  188. class FlatCAMGerber(FlatCAMObj, Gerber):
  189. """
  190. Represents Gerber code.
  191. """
  192. def __init__(self, name):
  193. Gerber.__init__(self)
  194. FlatCAMObj.__init__(self, name)
  195. self.kind = "gerber"
  196. # The 'name' is already in self.options from FlatCAMObj
  197. self.options.update({
  198. "plot": True,
  199. "mergepolys": True,
  200. "multicolored": False,
  201. "solid": False,
  202. "isotooldia": 0.016,
  203. "isopasses": 1,
  204. "isooverlap": 0.15,
  205. "cutouttooldia": 0.07,
  206. "cutoutmargin": 0.2,
  207. "cutoutgapsize": 0.15,
  208. "gaps": "tb",
  209. "noncoppermargin": 0.0,
  210. "noncopperrounded": False,
  211. "bboxmargin": 0.0,
  212. "bboxrounded": False
  213. })
  214. # The 'name' is already in self.form_kinds from FlatCAMObj
  215. self.form_kinds.update({
  216. "plot": "cb",
  217. "mergepolys": "cb",
  218. "multicolored": "cb",
  219. "solid": "cb",
  220. "isotooldia": "entry_eval",
  221. "isopasses": "entry_eval",
  222. "isooverlap": "entry_eval",
  223. "cutouttooldia": "entry_eval",
  224. "cutoutmargin": "entry_eval",
  225. "cutoutgapsize": "entry_eval",
  226. "gaps": "radio",
  227. "noncoppermargin": "entry_eval",
  228. "noncopperrounded": "cb",
  229. "bboxmargin": "entry_eval",
  230. "bboxrounded": "cb"
  231. })
  232. self.radios = {"gaps": {"rb_2tb": "tb", "rb_2lr": "lr", "rb_4": "4"}}
  233. self.radios_inv = {"gaps": {"tb": "rb_2tb", "lr": "rb_2lr", "4": "rb_4"}}
  234. # Attributes to be included in serialization
  235. # Always append to it because it carries contents
  236. # from predecessors.
  237. self.ser_attrs += ['options', 'kind']
  238. def convert_units(self, units):
  239. """
  240. Converts the units of the object by scaling dimensions in all geometry
  241. and options.
  242. :param units: Units to which to convert the object: "IN" or "MM".
  243. :type units: str
  244. :return: None
  245. :rtype: None
  246. """
  247. factor = Gerber.convert_units(self, units)
  248. self.options['isotooldia'] *= factor
  249. self.options['cutoutmargin'] *= factor
  250. self.options['cutoutgapsize'] *= factor
  251. self.options['noncoppermargin'] *= factor
  252. self.options['bboxmargin'] *= factor
  253. def plot(self):
  254. # Does all the required setup and returns False
  255. # if the 'ptint' option is set to False.
  256. if not FlatCAMObj.plot(self):
  257. return
  258. if self.options["mergepolys"]:
  259. geometry = self.solid_geometry
  260. else:
  261. geometry = self.buffered_paths + \
  262. [poly['polygon'] for poly in self.regions] + \
  263. self.flash_geometry
  264. if self.options["multicolored"]:
  265. linespec = '-'
  266. else:
  267. linespec = 'k-'
  268. if self.options["solid"]:
  269. for poly in geometry:
  270. # TODO: Too many things hardcoded.
  271. patch = PolygonPatch(poly,
  272. facecolor="#BBF268",
  273. edgecolor="#006E20",
  274. alpha=0.75,
  275. zorder=2)
  276. self.axes.add_patch(patch)
  277. else:
  278. for poly in geometry:
  279. x, y = poly.exterior.xy
  280. self.axes.plot(x, y, linespec)
  281. for ints in poly.interiors:
  282. x, y = ints.coords.xy
  283. self.axes.plot(x, y, linespec)
  284. # self.app.plotcanvas.auto_adjust_axes()
  285. GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  286. def serialize(self):
  287. return {
  288. "options": self.options,
  289. "kind": self.kind
  290. }
  291. class FlatCAMExcellon(FlatCAMObj, Excellon):
  292. """
  293. Represents Excellon/Drill code.
  294. """
  295. def __init__(self, name):
  296. Excellon.__init__(self)
  297. FlatCAMObj.__init__(self, name)
  298. self.kind = "excellon"
  299. self.options.update({
  300. "plot": True,
  301. "solid": False,
  302. "drillz": -0.1,
  303. "travelz": 0.1,
  304. "feedrate": 5.0,
  305. "toolselection": ""
  306. })
  307. self.form_kinds.update({
  308. "plot": "cb",
  309. "solid": "cb",
  310. "drillz": "entry_eval",
  311. "travelz": "entry_eval",
  312. "feedrate": "entry_eval",
  313. "toolselection": "entry_text"
  314. })
  315. # TODO: Document this.
  316. self.tool_cbs = {}
  317. # Attributes to be included in serialization
  318. # Always append to it because it carries contents
  319. # from predecessors.
  320. self.ser_attrs += ['options', 'kind']
  321. def convert_units(self, units):
  322. factor = Excellon.convert_units(self, units)
  323. self.options['drillz'] *= factor
  324. self.options['travelz'] *= factor
  325. self.options['feedrate'] *= factor
  326. def plot(self):
  327. # Does all the required setup and returns False
  328. # if the 'ptint' option is set to False.
  329. if not FlatCAMObj.plot(self):
  330. return
  331. try:
  332. _ = iter(self.solid_geometry)
  333. except TypeError:
  334. self.solid_geometry = [self.solid_geometry]
  335. # Plot excellon (All polygons?)
  336. if self.options["solid"]:
  337. for geo in self.solid_geometry:
  338. patch = PolygonPatch(geo,
  339. facecolor="#C40000",
  340. edgecolor="#750000",
  341. alpha=0.75,
  342. zorder=3)
  343. self.axes.add_patch(patch)
  344. else:
  345. for geo in self.solid_geometry:
  346. x, y = geo.exterior.coords.xy
  347. self.axes.plot(x, y, 'r-')
  348. for ints in geo.interiors:
  349. x, y = ints.coords.xy
  350. self.axes.plot(x, y, 'g-')
  351. #self.app.plotcanvas.auto_adjust_axes()
  352. GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  353. def show_tool_chooser(self):
  354. win = Gtk.Window()
  355. box = Gtk.Box(spacing=2)
  356. box.set_orientation(Gtk.Orientation(1))
  357. win.add(box)
  358. for tool in self.tools:
  359. self.tool_cbs[tool] = Gtk.CheckButton(label=tool + ": " + str(self.tools[tool]))
  360. box.pack_start(self.tool_cbs[tool], False, False, 1)
  361. button = Gtk.Button(label="Accept")
  362. box.pack_start(button, False, False, 1)
  363. win.show_all()
  364. def on_accept(widget):
  365. win.destroy()
  366. tool_list = []
  367. for toolx in self.tool_cbs:
  368. if self.tool_cbs[toolx].get_active():
  369. tool_list.append(toolx)
  370. self.options["toolselection"] = ", ".join(tool_list)
  371. self.to_form()
  372. button.connect("activate", on_accept)
  373. button.connect("clicked", on_accept)
  374. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  375. """
  376. Represents G-Code.
  377. """
  378. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  379. feedrate=3.0, z_cut=-0.002, tooldia=0.0):
  380. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  381. feedrate=feedrate, z_cut=z_cut, tooldia=tooldia)
  382. FlatCAMObj.__init__(self, name)
  383. self.kind = "cncjob"
  384. self.options.update({
  385. "plot": True,
  386. "tooldia": 0.4 / 25.4 # 0.4mm in inches
  387. })
  388. self.form_kinds.update({
  389. "plot": "cb",
  390. "tooldia": "entry_eval"
  391. })
  392. # Attributes to be included in serialization
  393. # Always append to it because it carries contents
  394. # from predecessors.
  395. self.ser_attrs += ['options', 'kind']
  396. def plot(self):
  397. # Does all the required setup and returns False
  398. # if the 'ptint' option is set to False.
  399. if not FlatCAMObj.plot(self):
  400. return
  401. self.plot2(self.axes, tooldia=self.options["tooldia"])
  402. #self.app.plotcanvas.auto_adjust_axes()
  403. GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  404. def convert_units(self, units):
  405. factor = CNCjob.convert_units(self, units)
  406. print "FlatCAMCNCjob.convert_units()"
  407. self.options["tooldia"] *= factor
  408. class FlatCAMGeometry(FlatCAMObj, Geometry):
  409. """
  410. Geometric object not associated with a specific
  411. format.
  412. """
  413. def __init__(self, name):
  414. FlatCAMObj.__init__(self, name)
  415. Geometry.__init__(self)
  416. self.kind = "geometry"
  417. self.options.update({
  418. "plot": True,
  419. "solid": False,
  420. "multicolored": False,
  421. "cutz": -0.002,
  422. "travelz": 0.1,
  423. "feedrate": 5.0,
  424. "cnctooldia": 0.4 / 25.4,
  425. "painttooldia": 0.0625,
  426. "paintoverlap": 0.15,
  427. "paintmargin": 0.01
  428. })
  429. self.form_kinds.update({
  430. "plot": "cb",
  431. "solid": "cb",
  432. "multicolored": "cb",
  433. "cutz": "entry_eval",
  434. "travelz": "entry_eval",
  435. "feedrate": "entry_eval",
  436. "cnctooldia": "entry_eval",
  437. "painttooldia": "entry_eval",
  438. "paintoverlap": "entry_eval",
  439. "paintmargin": "entry_eval"
  440. })
  441. # Attributes to be included in serialization
  442. # Always append to it because it carries contents
  443. # from predecessors.
  444. self.ser_attrs += ['options', 'kind']
  445. def scale(self, factor):
  446. """
  447. Scales all geometry by a given factor.
  448. :param factor: Factor by which to scale the object's geometry/
  449. :type factor: float
  450. :return: None
  451. :rtype: None
  452. """
  453. if type(self.solid_geometry) == list:
  454. self.solid_geometry = [affinity.scale(g, factor, factor, origin=(0, 0))
  455. for g in self.solid_geometry]
  456. else:
  457. self.solid_geometry = affinity.scale(self.solid_geometry, factor, factor,
  458. origin=(0, 0))
  459. def offset(self, vect):
  460. """
  461. Offsets all geometry by a given vector/
  462. :param vect: (x, y) vector by which to offset the object's geometry.
  463. :type vect: tuple
  464. :return: None
  465. :rtype: None
  466. """
  467. dx, dy = vect
  468. if type(self.solid_geometry) == list:
  469. self.solid_geometry = [affinity.translate(g, xoff=dx, yoff=dy)
  470. for g in self.solid_geometry]
  471. else:
  472. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  473. def convert_units(self, units):
  474. factor = Geometry.convert_units(self, units)
  475. self.options['cutz'] *= factor
  476. self.options['travelz'] *= factor
  477. self.options['feedrate'] *= factor
  478. self.options['cnctooldia'] *= factor
  479. self.options['painttooldia'] *= factor
  480. self.options['paintmargin'] *= factor
  481. return factor
  482. def plot(self):
  483. """
  484. Plots the object into its axes. If None, of if the axes
  485. are not part of the app's figure, it fetches new ones.
  486. :return: None
  487. """
  488. # Does all the required setup and returns False
  489. # if the 'ptint' option is set to False.
  490. if not FlatCAMObj.plot(self):
  491. return
  492. # Make sure solid_geometry is iterable.
  493. try:
  494. _ = iter(self.solid_geometry)
  495. except TypeError:
  496. self.solid_geometry = [self.solid_geometry]
  497. for geo in self.solid_geometry:
  498. if type(geo) == Polygon:
  499. x, y = geo.exterior.coords.xy
  500. self.axes.plot(x, y, 'r-')
  501. for ints in geo.interiors:
  502. x, y = ints.coords.xy
  503. self.axes.plot(x, y, 'r-')
  504. continue
  505. if type(geo) == LineString or type(geo) == LinearRing:
  506. x, y = geo.coords.xy
  507. self.axes.plot(x, y, 'r-')
  508. continue
  509. if type(geo) == MultiPolygon:
  510. for poly in geo:
  511. x, y = poly.exterior.coords.xy
  512. self.axes.plot(x, y, 'r-')
  513. for ints in poly.interiors:
  514. x, y = ints.coords.xy
  515. self.axes.plot(x, y, 'r-')
  516. continue
  517. print "WARNING: Did not plot:", str(type(geo))
  518. #self.app.plotcanvas.auto_adjust_axes()
  519. GLib.idle_add(self.app.plotcanvas.auto_adjust_axes)
  520. ########################################
  521. ## App ##
  522. ########################################
  523. class App:
  524. """
  525. The main application class. The constructor starts the GUI.
  526. """
  527. def __init__(self):
  528. """
  529. Starts the application. Takes no parameters.
  530. :return: app
  531. :rtype: App
  532. """
  533. # Needed to interact with the GUI from other threads.
  534. GObject.threads_init()
  535. # GLib.log_set_handler()
  536. #### GUI ####
  537. self.gladefile = "FlatCAM.ui"
  538. self.builder = Gtk.Builder()
  539. self.builder.add_from_file(self.gladefile)
  540. self.window = self.builder.get_object("window1")
  541. self.position_label = self.builder.get_object("label3")
  542. self.grid = self.builder.get_object("grid1")
  543. self.notebook = self.builder.get_object("notebook1")
  544. self.info_label = self.builder.get_object("label_status")
  545. self.progress_bar = self.builder.get_object("progressbar")
  546. self.progress_bar.set_show_text(True)
  547. self.units_label = self.builder.get_object("label_units")
  548. self.toolbar = self.builder.get_object("toolbar_main")
  549. # White (transparent) background on the "Options" tab.
  550. self.builder.get_object("vp_options").override_background_color(Gtk.StateType.NORMAL,
  551. Gdk.RGBA(1, 1, 1, 1))
  552. # Combo box to choose between project and application options.
  553. self.combo_options = self.builder.get_object("combo_options")
  554. self.combo_options.set_active(1)
  555. self.setup_project_list() # The "Project" tab
  556. self.setup_component_editor() # The "Selected" tab
  557. self.setup_toolbar()
  558. #### Event handling ####
  559. self.builder.connect_signals(self)
  560. #### Make plot area ####
  561. self.plotcanvas = PlotCanvas(self.grid)
  562. self.plotcanvas.mpl_connect('button_press_event', self.on_click_over_plot)
  563. self.plotcanvas.mpl_connect('motion_notify_event', self.on_mouse_move_over_plot)
  564. self.plotcanvas.mpl_connect('key_press_event', self.on_key_over_plot)
  565. self.setup_tooltips()
  566. #### DATA ####
  567. self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
  568. self.setup_obj_classes()
  569. self.stuff = {} # FlatCAMObj's by name
  570. self.mouse = None # Mouse coordinates over plot
  571. self.recent = []
  572. # What is selected by the user. It is
  573. # a key if self.stuff
  574. self.selected_item_name = None
  575. # Used to inhibit the on_options_update callback when
  576. # the options are being changed by the program and not the user.
  577. self.options_update_ignore = False
  578. self.toggle_units_ignore = False
  579. self.defaults = {
  580. "units": "in"
  581. } # Application defaults
  582. ## Current Project ##
  583. self.options = {} # Project options
  584. self.project_filename = None
  585. self.form_kinds = {
  586. "units": "radio"
  587. }
  588. self.radios = {"units": {"rb_inch": "IN", "rb_mm": "MM"},
  589. "gerber_gaps": {"rb_app_2tb": "tb", "rb_app_2lr": "lr", "rb_app_4": "4"}}
  590. self.radios_inv = {"units": {"IN": "rb_inch", "MM": "rb_mm"},
  591. "gerber_gaps": {"tb": "rb_app_2tb", "lr": "rb_app_2lr", "4": "rb_app_4"}}
  592. # Options for each kind of FlatCAMObj.
  593. # Example: 'gerber_plot': 'cb'. The widget name would be: 'cb_app_gerber_plot'
  594. for FlatCAMClass in [FlatCAMExcellon, FlatCAMGeometry, FlatCAMGerber, FlatCAMCNCjob]:
  595. obj = FlatCAMClass("no_name")
  596. for option in obj.form_kinds:
  597. self.form_kinds[obj.kind + "_" + option] = obj.form_kinds[option]
  598. # if obj.form_kinds[option] == "radio":
  599. # self.radios.update({obj.kind + "_" + option: obj.radios[option]})
  600. # self.radios_inv.update({obj.kind + "_" + option: obj.radios_inv[option]})
  601. ## Event subscriptions ##
  602. self.plot_click_subscribers = {}
  603. self.plot_mousemove_subscribers = {}
  604. ## Tools ##
  605. self.measure = Measurement(self.builder.get_object("box39"), self.plotcanvas.axes,
  606. self.plot_click_subscribers, self.plot_mousemove_subscribers)
  607. # Toolbar icon
  608. # TODO: Where should I put this? Tool should have a method to add to toolbar?
  609. meas_ico = Gtk.Image.new_from_file('share/measure32.png')
  610. measure = Gtk.ToolButton.new(meas_ico, "")
  611. measure.connect("clicked", self.measure.toggle_active)
  612. measure.set_tooltip_markup("<b>Measure Tool:</b> Enable/disable tool.\n" +
  613. "Click on point to set reference.\n" +
  614. "(Click on plot and hit <b>m</b>)")
  615. self.toolbar.insert(measure, -1)
  616. #### Initialization ####
  617. self.load_defaults()
  618. self.options.update(self.defaults) # Copy app defaults to project options
  619. self.options2form() # Populate the app defaults form
  620. self.units_label.set_text("[" + self.options["units"] + "]")
  621. self.setup_recent_items()
  622. #### Check for updates ####
  623. self.version = 3
  624. t1 = threading.Thread(target=self.versionCheck)
  625. t1.daemon = True
  626. t1.start()
  627. #### For debugging only ###
  628. def somethreadfunc(app_obj):
  629. print "Hello World!"
  630. t = threading.Thread(target=somethreadfunc, args=(self,))
  631. t.daemon = True
  632. t.start()
  633. ########################################
  634. ## START ##
  635. ########################################
  636. self.icon256 = GdkPixbuf.Pixbuf.new_from_file('share/flatcam_icon256.png')
  637. self.icon48 = GdkPixbuf.Pixbuf.new_from_file('share/flatcam_icon48.png')
  638. self.icon16 = GdkPixbuf.Pixbuf.new_from_file('share/flatcam_icon16.png')
  639. Gtk.Window.set_default_icon_list([self.icon16, self.icon48, self.icon256])
  640. self.window.set_title("FlatCAM - Alpha 3 UNSTABLE - Check for updates!")
  641. self.window.set_default_size(900, 600)
  642. self.window.show_all()
  643. def setup_toolbar(self):
  644. # Zoom fit
  645. zf_ico = Gtk.Image.new_from_file('share/zoom_fit32.png')
  646. zoom_fit = Gtk.ToolButton.new(zf_ico, "")
  647. zoom_fit.connect("clicked", self.on_zoom_fit)
  648. zoom_fit.set_tooltip_markup("Zoom Fit.\n(Click on plot and hit <b>1</b>)")
  649. self.toolbar.insert(zoom_fit, -1)
  650. # Zoom out
  651. zo_ico = Gtk.Image.new_from_file('share/zoom_out32.png')
  652. zoom_out = Gtk.ToolButton.new(zo_ico, "")
  653. zoom_out.connect("clicked", self.on_zoom_out)
  654. zoom_out.set_tooltip_markup("Zoom Out.\n(Click on plot and hit <b>2</b>)")
  655. self.toolbar.insert(zoom_out, -1)
  656. # Zoom in
  657. zi_ico = Gtk.Image.new_from_file('share/zoom_in32.png')
  658. zoom_in = Gtk.ToolButton.new(zi_ico, "")
  659. zoom_in.connect("clicked", self.on_zoom_in)
  660. zoom_in.set_tooltip_markup("Zoom In.\n(Click on plot and hit <b>3</b>)")
  661. self.toolbar.insert(zoom_in, -1)
  662. # Clear plot
  663. cp_ico = Gtk.Image.new_from_file('share/clear_plot32.png')
  664. clear_plot = Gtk.ToolButton.new(cp_ico, "")
  665. clear_plot.connect("clicked", self.on_clear_plots)
  666. clear_plot.set_tooltip_markup("Clear Plot")
  667. self.toolbar.insert(clear_plot, -1)
  668. # Replot
  669. rp_ico = Gtk.Image.new_from_file('share/replot32.png')
  670. replot = Gtk.ToolButton.new(rp_ico, "")
  671. replot.connect("clicked", self.on_toolbar_replot)
  672. replot.set_tooltip_markup("Re-plot all")
  673. self.toolbar.insert(replot, -1)
  674. # Delete item
  675. del_ico = Gtk.Image.new_from_file('share/delete32.png')
  676. delete = Gtk.ToolButton.new(del_ico, "")
  677. delete.connect("clicked", self.on_delete)
  678. delete.set_tooltip_markup("Delete selected\nobject.")
  679. self.toolbar.insert(delete, -1)
  680. def setup_obj_classes(self):
  681. """
  682. Sets up application specifics on the FlatCAMObj class.
  683. :return: None
  684. """
  685. FlatCAMObj.app = self
  686. def setup_project_list(self):
  687. """
  688. Sets up list or Tree where whatever has been loaded or created is
  689. displayed.
  690. :return: None
  691. """
  692. self.store = Gtk.ListStore(str)
  693. self.tree = Gtk.TreeView(self.store)
  694. #self.list = Gtk.ListBox()
  695. self.tree.connect("row_activated", self.on_row_activated)
  696. self.tree_select = self.tree.get_selection()
  697. self.signal_id = self.tree_select.connect("changed", self.on_tree_selection_changed)
  698. renderer = Gtk.CellRendererText()
  699. column = Gtk.TreeViewColumn("Objects", renderer, text=0)
  700. self.tree.append_column(column)
  701. self.builder.get_object("box_project").pack_start(self.tree, False, False, 1)
  702. def setup_component_editor(self):
  703. """
  704. Initial configuration of the component editor. Creates
  705. a page titled "Selection" on the notebook on the left
  706. side of the main window.
  707. :return: None
  708. """
  709. box_selected = self.builder.get_object("box_selected")
  710. # Remove anything else in the box
  711. box_children = box_selected.get_children()
  712. for child in box_children:
  713. box_selected.remove(child)
  714. box1 = Gtk.Box(Gtk.Orientation.VERTICAL)
  715. label1 = Gtk.Label("Choose an item from Project")
  716. box1.pack_start(label1, True, False, 1)
  717. box_selected.pack_start(box1, True, True, 0)
  718. #box_selected.show()
  719. box1.show()
  720. label1.show()
  721. def setup_recent_items(self):
  722. icons = {
  723. "gerber": "share/flatcam_icon16.png",
  724. "excellon": "share/drill16.png",
  725. "cncjob": "share/cnc16.png",
  726. "project": "share/project16.png"
  727. }
  728. try:
  729. f = open('recent.json')
  730. except:
  731. print "ERROR: Failed to load recent item list."
  732. self.info("Failed to load recent item list.")
  733. return
  734. try:
  735. self.recent = json.load(f)
  736. except:
  737. print "ERROR: Failed to parse recent item list."
  738. self.info("Failed to parse recent item list.")
  739. f.close()
  740. return
  741. f.close()
  742. recent_menu = Gtk.Menu()
  743. for recent in self.recent:
  744. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  745. item = Gtk.ImageMenuItem.new_with_label(filename)
  746. im = Gtk.Image.new_from_file(icons[recent["kind"]])
  747. item.set_image(im)
  748. # def opener():
  749. recent_menu.append(item)
  750. self.builder.get_object('open_recent').set_submenu(recent_menu)
  751. recent_menu.show_all()
  752. def info(self, text):
  753. """
  754. Show text on the status bar.
  755. :param text: Text to display.
  756. :type text: str
  757. :return: None
  758. """
  759. self.info_label.set_text(text)
  760. def build_list(self):
  761. """
  762. Clears and re-populates the list of objects in currently
  763. in the project.
  764. :return: None
  765. """
  766. print "build_list(): clearing"
  767. self.tree_select.unselect_all()
  768. self.store.clear()
  769. print "repopulating...",
  770. for key in self.stuff:
  771. print key,
  772. self.store.append([key])
  773. print
  774. def get_radio_value(self, radio_set):
  775. """
  776. Returns the radio_set[key] of the radiobutton
  777. whose name is key is active.
  778. :param radio_set: A dictionary containing widget_name: value pairs.
  779. :type radio_set: dict
  780. :return: radio_set[key]
  781. """
  782. for name in radio_set:
  783. if self.builder.get_object(name).get_active():
  784. return radio_set[name]
  785. def plot_all(self):
  786. """
  787. Re-generates all plots from all objects.
  788. :return: None
  789. """
  790. self.plotcanvas.clear()
  791. self.set_progress_bar(0.1, "Re-plotting...")
  792. def thread_func(app_obj):
  793. percentage = 0.1
  794. try:
  795. delta = 0.9 / len(self.stuff)
  796. except ZeroDivisionError:
  797. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, ""))
  798. return
  799. for i in self.stuff:
  800. self.stuff[i].plot()
  801. percentage += delta
  802. GLib.idle_add(lambda: app_obj.set_progress_bar(percentage, "Re-plotting..."))
  803. GLib.idle_add(app_obj.plotcanvas.auto_adjust_axes)
  804. GLib.idle_add(lambda: self.on_zoom_fit(None))
  805. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, ""))
  806. t = threading.Thread(target=thread_func, args=(self,))
  807. t.daemon = True
  808. t.start()
  809. def get_eval(self, widget_name):
  810. """
  811. Runs eval() on the on the text entry of name 'widget_name'
  812. and returns the results.
  813. :param widget_name: Name of Gtk.Entry
  814. :type widget_name: str
  815. :return: Depends on contents of the entry text.
  816. """
  817. value = self.builder.get_object(widget_name).get_text()
  818. if value == "":
  819. value = "None"
  820. try:
  821. evald = eval(value)
  822. return evald
  823. except:
  824. self.info("Could not evaluate: " + value)
  825. return None
  826. def set_list_selection(self, name):
  827. """
  828. Marks a given object as selected in the list ob objects
  829. in the GUI. This selection will in turn trigger
  830. ``self.on_tree_selection_changed()``.
  831. :param name: Name of the object.
  832. :type name: str
  833. :return: None
  834. """
  835. iter = self.store.get_iter_first()
  836. while iter is not None and self.store[iter][0] != name:
  837. iter = self.store.iter_next(iter)
  838. self.tree_select.unselect_all()
  839. self.tree_select.select_iter(iter)
  840. # Need to return False such that GLib.idle_add
  841. # or .timeout_add do not repeat.
  842. return False
  843. def new_object(self, kind, name, initialize):
  844. """
  845. Creates a new specalized FlatCAMObj and attaches it to the application,
  846. this is, updates the GUI accordingly, any other records and plots it.
  847. :param kind: The kind of object to create. One of 'gerber',
  848. 'excellon', 'cncjob' and 'geometry'.
  849. :type kind: str
  850. :param name: Name for the object.
  851. :type name: str
  852. :param initialize: Function to run after creation of the object
  853. but before it is attached to the application. The function is
  854. called with 2 parameters: the new object and the App instance.
  855. :type initialize: function
  856. :return: None
  857. :rtype: None
  858. """
  859. ### Check for existing name
  860. if name in self.stuff:
  861. ## Create a new name
  862. # Ends with number?
  863. match = re.search(r'(.*[^\d])?(\d+)$', name)
  864. if match: # Yes: Increment the number!
  865. base = match.group(1) or ''
  866. num = int(match.group(2))
  867. name = base + str(num + 1)
  868. else: # No: add a number!
  869. name += "_1"
  870. # Create object
  871. classdict = {
  872. "gerber": FlatCAMGerber,
  873. "excellon": FlatCAMExcellon,
  874. "cncjob": FlatCAMCNCjob,
  875. "geometry": FlatCAMGeometry
  876. }
  877. obj = classdict[kind](name)
  878. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  879. # Initialize as per user request
  880. # User must take care to implement initialize
  881. # in a thread-safe way as is is likely that we
  882. # have been invoked in a separate thread.
  883. #initialize(obj, self)
  884. # Set default options from self.options
  885. for option in self.options:
  886. if option.find(kind + "_") == 0:
  887. oname = option[len(kind)+1:]
  888. obj.options[oname] = self.options[option]
  889. # Initialize as per user request
  890. # User must take care to implement initialize
  891. # in a thread-safe way as is is likely that we
  892. # have been invoked in a separate thread.
  893. initialize(obj, self)
  894. # Check units and convert if necessary
  895. if self.options["units"].upper() != obj.units.upper():
  896. GLib.idle_add(lambda: self.info("Converting units to " + self.options["units"] + "."))
  897. obj.convert_units(self.options["units"])
  898. # Add to our records
  899. self.stuff[name] = obj
  900. # Update GUI list and select it (Thread-safe?)
  901. self.store.append([name])
  902. #self.build_list()
  903. GLib.idle_add(lambda: self.set_list_selection(name))
  904. # TODO: Gtk.notebook.set_current_page is not known to
  905. # TODO: return False. Fix this??
  906. GLib.timeout_add(100, lambda: self.notebook.set_current_page(1))
  907. # Plot
  908. # TODO: (Thread-safe?)
  909. obj.plot()
  910. # TODO: Threading dissaster!
  911. GLib.idle_add(lambda: self.on_zoom_fit(None))
  912. return obj
  913. def set_progress_bar(self, percentage, text=""):
  914. """
  915. Sets the application's progress bar to a given frac_digits and text.
  916. :param percentage: The frac_digits (0.0-1.0) of the progress.
  917. :type percentage: float
  918. :param text: Text to display on the progress bar.
  919. :type text: str
  920. :return: None
  921. """
  922. self.progress_bar.set_text(text)
  923. self.progress_bar.set_fraction(percentage)
  924. return False
  925. def get_current(self):
  926. """
  927. Returns the currently selected FlatCAMObj in the application.
  928. :return: Currently selected FlatCAMObj in the application.
  929. :rtype: FlatCAMObj or None
  930. """
  931. # TODO: Could possibly read the form into the object here.
  932. # But there are some cases when the form for the object
  933. # is not up yet. See on_tree_selection_changed.
  934. try:
  935. return self.stuff[self.selected_item_name]
  936. except:
  937. return None
  938. def load_defaults(self):
  939. """
  940. Loads the aplication's default settings from defaults.json into
  941. ``self.defaults``.
  942. :return: None
  943. """
  944. try:
  945. f = open("defaults.json")
  946. options = f.read()
  947. f.close()
  948. except:
  949. self.info("ERROR: Could not load defaults file.")
  950. return
  951. try:
  952. defaults = json.loads(options)
  953. except:
  954. e = sys.exc_info()[0]
  955. print e
  956. self.info("ERROR: Failed to parse defaults file.")
  957. return
  958. self.defaults.update(defaults)
  959. def read_form(self):
  960. """
  961. Reads the options form into self.defaults/self.options.
  962. :return: None
  963. :rtype: None
  964. """
  965. combo_sel = self.combo_options.get_active()
  966. options_set = [self.options, self.defaults][combo_sel]
  967. for option in options_set:
  968. self.read_form_item(option, options_set)
  969. def read_form_item(self, name, dest):
  970. """
  971. Reads the value of a form item in the defaults/options form and
  972. saves it to the corresponding dictionary.
  973. :param name: Name of the form item. A key in ``self.defaults`` or
  974. ``self.options``.
  975. :type name: str
  976. :param dest: Dictionary to which to save the value.
  977. :type dest: dict
  978. :return: None
  979. """
  980. fkind = self.form_kinds[name]
  981. fname = fkind + "_" + "app" + "_" + name
  982. if fkind == 'entry_text':
  983. dest[name] = self.builder.get_object(fname).get_text()
  984. return
  985. if fkind == 'entry_eval':
  986. dest[name] = self.get_eval(fname)
  987. return
  988. if fkind == 'cb':
  989. dest[name] = self.builder.get_object(fname).get_active()
  990. return
  991. if fkind == 'radio':
  992. dest[name] = self.get_radio_value(self.radios[name])
  993. return
  994. print "Unknown kind of form item:", fkind
  995. def options2form(self):
  996. """
  997. Sets the 'Project Options' or 'Application Defaults' form with values from
  998. ``self.options`` or ``self.defaults``.
  999. :return: None
  1000. :rtype: None
  1001. """
  1002. # Set the on-change callback to do nothing while we do the changes.
  1003. self.options_update_ignore = True
  1004. self.toggle_units_ignore = True
  1005. combo_sel = self.combo_options.get_active()
  1006. options_set = [self.options, self.defaults][combo_sel]
  1007. for option in options_set:
  1008. self.set_form_item(option, options_set[option])
  1009. self.options_update_ignore = False
  1010. self.toggle_units_ignore = False
  1011. def set_form_item(self, name, value):
  1012. """
  1013. Sets a form item 'name' in the GUI with the given 'value'. The syntax of
  1014. form names in the GUI is <kind>_app_<name>, where kind is one of: rb (radio button),
  1015. cb (check button), entry_eval or entry_text (entry), combo (combo box). name is
  1016. whatever name it's been given. For self.defaults, name is a key in the dictionary.
  1017. :param name: Name of the form field.
  1018. :type name: str
  1019. :param value: The value to set the form field to.
  1020. :type value: Depends on field kind.
  1021. :return: None
  1022. """
  1023. if name not in self.form_kinds:
  1024. print "WARNING: Tried to set unknown option/form item:", name
  1025. return
  1026. fkind = self.form_kinds[name]
  1027. fname = fkind + "_" + "app" + "_" + name
  1028. if fkind == 'entry_eval' or fkind == 'entry_text':
  1029. try:
  1030. self.builder.get_object(fname).set_text(str(value))
  1031. except:
  1032. print "ERROR: Failed to set value of %s to %s" % (fname, str(value))
  1033. return
  1034. if fkind == 'cb':
  1035. try:
  1036. self.builder.get_object(fname).set_active(value)
  1037. except:
  1038. print "ERROR: Failed to set value of %s to %s" % (fname, str(value))
  1039. return
  1040. if fkind == 'radio':
  1041. try:
  1042. self.builder.get_object(self.radios_inv[name][value]).set_active(True)
  1043. except:
  1044. print "ERROR: Failed to set value of %s to %s" % (fname, str(value))
  1045. return
  1046. print "Unknown kind of form item:", fkind
  1047. def save_project(self, filename):
  1048. """
  1049. Saves the current project to the specified file.
  1050. :param filename: Name of the file in which to save.
  1051. :type filename: str
  1052. :return: None
  1053. """
  1054. # Capture the latest changes
  1055. try:
  1056. self.get_current().read_form()
  1057. except:
  1058. pass
  1059. d = {"objs": [self.stuff[o].to_dict() for o in self.stuff],
  1060. "options": self.options}
  1061. try:
  1062. f = open(filename, 'w')
  1063. except:
  1064. print "ERROR: Failed to open file for saving:", filename
  1065. return
  1066. try:
  1067. json.dump(d, f, default=to_dict)
  1068. except:
  1069. print "ERROR: File open but failed to write:", filename
  1070. f.close()
  1071. return
  1072. f.close()
  1073. def open_project(self, filename):
  1074. """
  1075. Loads a project from the specified file.
  1076. :param filename: Name of the file from which to load.
  1077. :type filename: str
  1078. :return: None
  1079. """
  1080. try:
  1081. f = open(filename, 'r')
  1082. except:
  1083. #print "WARNING: Failed to open project file:", filename
  1084. self.info("ERROR: Failed to open project file: %s" % filename)
  1085. return
  1086. try:
  1087. d = json.load(f, object_hook=dict2obj)
  1088. except:
  1089. #print sys.exc_info()
  1090. #print "WARNING: Failed to parse project file:", filename
  1091. self.info("ERROR: Failed to parse project file: %s" % filename)
  1092. f.close()
  1093. return
  1094. self.register_recent("project", filename)
  1095. # Clear the current project
  1096. self.on_file_new(None)
  1097. # Project options
  1098. self.options.update(d['options'])
  1099. self.project_filename = filename
  1100. self.units_label.set_text(self.options["units"])
  1101. # Re create objects
  1102. for obj in d['objs']:
  1103. def obj_init(obj_inst, app_inst):
  1104. obj_inst.from_dict(obj)
  1105. self.new_object(obj['kind'], obj['options']['name'], obj_init)
  1106. self.info("Project loaded from: " + filename)
  1107. def populate_objects_combo(self, combo):
  1108. """
  1109. Populates a Gtk.Comboboxtext with the list of the object in the project.
  1110. :param combo: Name or instance of the comboboxtext.
  1111. :type combo: str or Gtk.ComboBoxText
  1112. :return: None
  1113. """
  1114. print "Populating combo!"
  1115. if type(combo) == str:
  1116. combo = self.builder.get_object(combo)
  1117. combo.remove_all()
  1118. for obj in self.stuff:
  1119. combo.append_text(obj)
  1120. def versionCheck(self, *args):
  1121. """
  1122. Checks for the latest version of the program. Alerts the
  1123. user if theirs is outdated. This method is meant to be run
  1124. in a saeparate thread.
  1125. :return: None
  1126. """
  1127. try:
  1128. f = urllib.urlopen("http://caram.cl/flatcam/VERSION") # TODO: Hardcoded.
  1129. except:
  1130. GLib.idle_add(lambda: self.info("ERROR trying to check for latest version."))
  1131. return
  1132. try:
  1133. data = json.load(f)
  1134. except:
  1135. GLib.idle_add(lambda: self.info("ERROR trying to check for latest version."))
  1136. f.close()
  1137. return
  1138. f.close()
  1139. if self.version >= data["version"]:
  1140. GLib.idle_add(lambda: self.info("FlatCAM is up to date!"))
  1141. return
  1142. label = Gtk.Label("There is a newer version of FlatCAM\n" +
  1143. "available for download:\n\n" +
  1144. data["name"] + "\n\n" + data["message"])
  1145. dialog = Gtk.Dialog("Newer Version Available", self.window, 0,
  1146. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  1147. Gtk.STOCK_OK, Gtk.ResponseType.OK))
  1148. dialog.set_default_size(150, 100)
  1149. dialog.set_modal(True)
  1150. box = dialog.get_content_area()
  1151. box.set_border_width(10)
  1152. box.add(label)
  1153. def do_dialog():
  1154. dialog.show_all()
  1155. response = dialog.run()
  1156. dialog.destroy()
  1157. GLib.idle_add(lambda: do_dialog())
  1158. return
  1159. def setup_tooltips(self):
  1160. tooltips = {
  1161. "cb_gerber_plot": "Plot this object on the main window.",
  1162. "cb_gerber_mergepolys": "Show overlapping polygons as single.",
  1163. "cb_gerber_solid": "Paint inside polygons.",
  1164. "cb_gerber_multicolored": "Draw polygons with different colors."
  1165. }
  1166. for widget in tooltips:
  1167. self.builder.get_object(widget).set_tooltip_markup(tooltips[widget])
  1168. def do_nothing(self, param):
  1169. return
  1170. def disable_plots(self, except_current=False):
  1171. """
  1172. Disables all plots with exception of the current object if specified.
  1173. :param except_current: Wether to skip the current object.
  1174. :rtype except_current: boolean
  1175. :return: None
  1176. """
  1177. # TODO: This method is very similar to replot_all. Try to merge.
  1178. self.set_progress_bar(0.1, "Re-plotting...")
  1179. def thread_func(app_obj):
  1180. percentage = 0.1
  1181. try:
  1182. delta = 0.9 / len(self.stuff)
  1183. except ZeroDivisionError:
  1184. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, ""))
  1185. return
  1186. for i in self.stuff:
  1187. if i != app_obj.selected_item_name or not except_current:
  1188. self.stuff[i].options['plot'] = False
  1189. self.stuff[i].plot()
  1190. percentage += delta
  1191. GLib.idle_add(lambda: app_obj.set_progress_bar(percentage, "Re-plotting..."))
  1192. GLib.idle_add(app_obj.plotcanvas.auto_adjust_axes)
  1193. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, ""))
  1194. t = threading.Thread(target=thread_func, args=(self,))
  1195. t.daemon = True
  1196. t.start()
  1197. def enable_all_plots(self, *args):
  1198. self.plotcanvas.clear()
  1199. self.set_progress_bar(0.1, "Re-plotting...")
  1200. def thread_func(app_obj):
  1201. percentage = 0.1
  1202. try:
  1203. delta = 0.9 / len(self.stuff)
  1204. except ZeroDivisionError:
  1205. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, ""))
  1206. return
  1207. for i in self.stuff:
  1208. self.stuff[i].options['plot'] = True
  1209. self.stuff[i].plot()
  1210. percentage += delta
  1211. GLib.idle_add(lambda: app_obj.set_progress_bar(percentage, "Re-plotting..."))
  1212. GLib.idle_add(app_obj.plotcanvas.auto_adjust_axes)
  1213. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, ""))
  1214. t = threading.Thread(target=thread_func, args=(self,))
  1215. t.daemon = True
  1216. t.start()
  1217. def register_recent(self, kind, filename):
  1218. record = {'kind': kind, 'filename': filename}
  1219. if record in self.recent:
  1220. return
  1221. self.recent.insert(0, record)
  1222. if len(self.recent) > 10: # Limit reached
  1223. self.recent.pop()
  1224. try:
  1225. f = open('recent.json', 'w')
  1226. except:
  1227. print "ERROR: Failed to open recent items file for writing."
  1228. self.info('Failed to open recent files file for writing.')
  1229. return
  1230. try:
  1231. json.dump(self.recent, f)
  1232. except:
  1233. print "ERROR: Failed to write to recent items file."
  1234. self.info('Failed to write to recent items file.')
  1235. f.close()
  1236. f.close()
  1237. ########################################
  1238. ## EVENT HANDLERS ##
  1239. ########################################
  1240. def on_disable_all_plots(self, widget):
  1241. self.disable_plots()
  1242. def on_disable_all_plots_not_current(self, widget):
  1243. self.disable_plots(except_current=True)
  1244. def on_offset_object(self, widget):
  1245. """
  1246. Offsets the object's geometry by the vector specified
  1247. in the form. Re-plots.
  1248. :param widget: Ignored
  1249. :return: None
  1250. """
  1251. obj = self.get_current()
  1252. obj.read_form()
  1253. assert isinstance(obj, FlatCAMObj)
  1254. try:
  1255. vect = self.get_eval("entry_eval_" + obj.kind + "_offset")
  1256. except:
  1257. self.info("ERROR: Vector is not in (x, y) format.")
  1258. return
  1259. assert isinstance(obj, Geometry)
  1260. obj.offset(vect)
  1261. obj.plot()
  1262. return
  1263. def on_cb_plot_toggled(self, widget):
  1264. """
  1265. Callback for toggling the "Plot" checkbox. Re-plots.
  1266. :param widget: Ignored.
  1267. :return: None
  1268. """
  1269. self.get_current().read_form()
  1270. self.get_current().plot()
  1271. def on_about(self, widget):
  1272. """
  1273. Opens the 'About' dialog box.
  1274. :param widget: Ignored.
  1275. :return: None
  1276. """
  1277. about = self.builder.get_object("aboutdialog")
  1278. response = about.run()
  1279. #about.destroy()
  1280. about.hide()
  1281. def on_create_mirror(self, widget):
  1282. """
  1283. Creates a mirror image of an object to be used as a bottom layer.
  1284. :param widget: Ignored.
  1285. :return: None
  1286. """
  1287. # TODO: Move (some of) this to camlib!
  1288. # Object to mirror
  1289. try:
  1290. obj_name = self.builder.get_object("comboboxtext_bottomlayer").get_active_text()
  1291. fcobj = self.stuff[obj_name]
  1292. except KeyError:
  1293. self.info("WARNING: Cannot mirror that object.")
  1294. return
  1295. # For now, lets limit to Gerbers and Excellons.
  1296. # assert isinstance(gerb, FlatCAMGerber)
  1297. if not isinstance(fcobj, FlatCAMGerber) and not isinstance(fcobj, FlatCAMExcellon):
  1298. self.info("ERROR: Only Gerber and Excellon objects can be mirrored.")
  1299. return
  1300. # Mirror axis "X" or "Y
  1301. axis = self.get_radio_value({"rb_mirror_x": "X",
  1302. "rb_mirror_y": "Y"})
  1303. mode = self.get_radio_value({"rb_mirror_box": "box",
  1304. "rb_mirror_point": "point"})
  1305. if mode == "point": # A single point defines the mirror axis
  1306. # TODO: Error handling
  1307. px, py = eval(self.point_entry.get_text())
  1308. else: # The axis is the line dividing the box in the middle
  1309. name = self.box_combo.get_active_text()
  1310. bb_obj = self.stuff[name]
  1311. xmin, ymin, xmax, ymax = bb_obj.bounds()
  1312. px = 0.5*(xmin+xmax)
  1313. py = 0.5*(ymin+ymax)
  1314. # Do the mirroring
  1315. # xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1316. # mirrored = affinity.scale(fcobj.solid_geometry, xscale, yscale, origin=(px, py))
  1317. #
  1318. # def obj_init(obj_inst, app_inst):
  1319. # obj_inst.solid_geometry = mirrored
  1320. #
  1321. # self.new_object("gerber", fcobj.options["name"] + "_mirror", obj_init)
  1322. fcobj.mirror(axis, [px, py])
  1323. fcobj.plot()
  1324. #self.on_update_plot(None)
  1325. def on_create_aligndrill(self, widget):
  1326. """
  1327. Creates alignment holes Excellon object. Creates mirror duplicates
  1328. of the specified holes around the specified axis.
  1329. :param widget: Ignored.
  1330. :return: None
  1331. """
  1332. # Mirror axis. Same as in on_create_mirror.
  1333. axis = self.get_radio_value({"rb_mirror_x": "X",
  1334. "rb_mirror_y": "Y"})
  1335. # TODO: Error handling
  1336. mode = self.get_radio_value({"rb_mirror_box": "box",
  1337. "rb_mirror_point": "point"})
  1338. if mode == "point":
  1339. px, py = eval(self.point_entry.get_text())
  1340. else:
  1341. name = self.box_combo.get_active_text()
  1342. bb_obj = self.stuff[name]
  1343. xmin, ymin, xmax, ymax = bb_obj.bounds()
  1344. px = 0.5*(xmin+xmax)
  1345. py = 0.5*(ymin+ymax)
  1346. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1347. # Tools
  1348. dia = self.get_eval("entry_dblsided_alignholediam")
  1349. tools = {"1": {"C": dia}}
  1350. # Parse hole list
  1351. # TODO: Better parsing
  1352. holes = self.builder.get_object("entry_dblsided_alignholes").get_text()
  1353. holes = eval("[" + holes + "]")
  1354. drills = []
  1355. for hole in holes:
  1356. point = Point(hole)
  1357. point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py))
  1358. drills.append({"point": point, "tool": "1"})
  1359. drills.append({"point": point_mirror, "tool": "1"})
  1360. def obj_init(obj_inst, app_inst):
  1361. obj_inst.tools = tools
  1362. obj_inst.drills = drills
  1363. obj_inst.create_geometry()
  1364. self.new_object("excellon", "Alignment Drills", obj_init)
  1365. def on_toggle_pointbox(self, widget):
  1366. """
  1367. Callback for radio selection change between point and box in the
  1368. Double-sided PCB tool. Updates the UI accordingly.
  1369. :param widget: Ignored.
  1370. :return: None
  1371. """
  1372. # Where the entry or combo go
  1373. box = self.builder.get_object("box_pointbox")
  1374. # Clear contents
  1375. children = box.get_children()
  1376. for child in children:
  1377. box.remove(child)
  1378. choice = self.get_radio_value({"rb_mirror_point": "point",
  1379. "rb_mirror_box": "box"})
  1380. if choice == "point":
  1381. self.point_entry = Gtk.Entry()
  1382. self.builder.get_object("box_pointbox").pack_start(self.point_entry,
  1383. False, False, 1)
  1384. self.point_entry.show()
  1385. else:
  1386. self.box_combo = Gtk.ComboBoxText()
  1387. self.builder.get_object("box_pointbox").pack_start(self.box_combo,
  1388. False, False, 1)
  1389. self.populate_objects_combo(self.box_combo)
  1390. self.box_combo.show()
  1391. def on_tools_doublesided(self, param):
  1392. """
  1393. Callback for menu item Tools->Double Sided PCB Tool. Launches the
  1394. tool placing its UI in the "Tool" tab in the notebook.
  1395. :param param: Ignored.
  1396. :return: None
  1397. """
  1398. # Were are we drawing the UI
  1399. box_tool = self.builder.get_object("box_tool")
  1400. # Remove anything else in the box
  1401. box_children = box_tool.get_children()
  1402. for child in box_children:
  1403. box_tool.remove(child)
  1404. # Get the UI
  1405. osw = self.builder.get_object("offscreenwindow_dblsided")
  1406. sw = self.builder.get_object("sw_dblsided")
  1407. osw.remove(sw)
  1408. vp = self.builder.get_object("vp_dblsided")
  1409. vp.override_background_color(Gtk.StateType.NORMAL, Gdk.RGBA(1, 1, 1, 1))
  1410. # Put in the UI
  1411. box_tool.pack_start(sw, True, True, 0)
  1412. # INITIALIZATION
  1413. # Populate combo box
  1414. self.populate_objects_combo("comboboxtext_bottomlayer")
  1415. # Point entry
  1416. self.point_entry = Gtk.Entry()
  1417. box = self.builder.get_object("box_pointbox")
  1418. for child in box.get_children():
  1419. box.remove(child)
  1420. box.pack_start(self.point_entry, False, False, 1)
  1421. # Show the "Tool" tab
  1422. self.notebook.set_current_page(3)
  1423. sw.show_all()
  1424. def on_toggle_units(self, widget):
  1425. """
  1426. Callback for the Units radio-button change in the Options tab.
  1427. Changes the application's default units or the current project's units.
  1428. If changing the project's units, the change propagates to all of
  1429. the objects in the project.
  1430. :param widget: Ignored.
  1431. :return: None
  1432. """
  1433. if self.toggle_units_ignore:
  1434. return
  1435. combo_sel = self.combo_options.get_active()
  1436. options_set = [self.options, self.defaults][combo_sel]
  1437. # Options to scale
  1438. dimensions = ['gerber_isotooldia', 'gerber_cutoutmargin', 'gerber_cutoutgapsize',
  1439. 'gerber_noncoppermargin', 'gerber_bboxmargin', 'excellon_drillz',
  1440. 'excellon_travelz', 'excellon_feedrate', 'cncjob_tooldia',
  1441. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate',
  1442. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap',
  1443. 'geometry_paintmargin']
  1444. def scale_options(factor):
  1445. for dim in dimensions:
  1446. options_set[dim] *= factor
  1447. # The scaling factor depending on choice of units.
  1448. factor = 1/25.4
  1449. if self.builder.get_object('rb_mm').get_active():
  1450. factor = 25.4
  1451. # App units. Convert without warning.
  1452. if combo_sel == 1:
  1453. self.read_form()
  1454. scale_options(factor)
  1455. self.options2form()
  1456. return
  1457. # Changing project units. Warn user.
  1458. label = Gtk.Label("Changing the units of the project causes all geometrical \n" + \
  1459. "properties of all objects to be scaled accordingly. Continue?")
  1460. dialog = Gtk.Dialog("Changing Project Units", self.window, 0,
  1461. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  1462. Gtk.STOCK_OK, Gtk.ResponseType.OK))
  1463. dialog.set_default_size(150, 100)
  1464. dialog.set_modal(True)
  1465. box = dialog.get_content_area()
  1466. box.set_border_width(10)
  1467. box.add(label)
  1468. dialog.show_all()
  1469. response = dialog.run()
  1470. dialog.destroy()
  1471. if response == Gtk.ResponseType.OK:
  1472. #print "Converting units..."
  1473. #print "Converting options..."
  1474. self.read_form()
  1475. scale_options(factor)
  1476. self.options2form()
  1477. for obj in self.stuff:
  1478. units = self.get_radio_value({"rb_mm": "MM", "rb_inch": "IN"})
  1479. #print "Converting ", obj, " to ", units
  1480. self.stuff[obj].convert_units(units)
  1481. current = self.get_current()
  1482. if current is not None:
  1483. current.to_form()
  1484. self.plot_all()
  1485. else:
  1486. # Undo toggling
  1487. self.toggle_units_ignore = True
  1488. if self.builder.get_object('rb_mm').get_active():
  1489. self.builder.get_object('rb_inch').set_active(True)
  1490. else:
  1491. self.builder.get_object('rb_mm').set_active(True)
  1492. self.toggle_units_ignore = False
  1493. self.read_form()
  1494. self.info("Converted units to %s" % self.options["units"])
  1495. self.units_label.set_text("[" + self.options["units"] + "]")
  1496. def on_file_openproject(self, param):
  1497. """
  1498. Callback for menu item File->Open Project. Opens a file chooser and calls
  1499. ``self.open_project()`` after successful selection of a filename.
  1500. :param param: Ignored.
  1501. :return: None
  1502. """
  1503. def on_success(app_obj, filename):
  1504. app_obj.open_project(filename)
  1505. self.file_chooser_action(on_success)
  1506. def on_file_saveproject(self, param):
  1507. """
  1508. Callback for menu item File->Save Project. Saves the project to
  1509. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  1510. if set to None. The project is saved by calling ``self.save_project()``.
  1511. :param param: Ignored.
  1512. :return: None
  1513. """
  1514. if self.project_filename is None:
  1515. self.on_file_saveprojectas(None)
  1516. else:
  1517. self.save_project(self.project_filename)
  1518. self.register_recent("project", self.project_filename)
  1519. self.info("Project saved to: " + self.project_filename)
  1520. def on_file_saveprojectas(self, param):
  1521. """
  1522. Callback for menu item File->Save Project As... Opens a file
  1523. chooser and saves the project to the given file via
  1524. ``self.save_project()``.
  1525. :param param: Ignored.
  1526. :return: None
  1527. """
  1528. def on_success(app_obj, filename):
  1529. assert isinstance(app_obj, App)
  1530. app_obj.save_project(filename)
  1531. self.project_filename = filename
  1532. self.register_recent("project", filename)
  1533. app_obj.info("Project saved to: " + filename)
  1534. self.file_chooser_save_action(on_success)
  1535. def on_file_saveprojectcopy(self, param):
  1536. """
  1537. Callback for menu item File->Save Project Copy... Opens a file
  1538. chooser and saves the project to the given file via
  1539. ``self.save_project``. It does not update ``self.project_filename`` so
  1540. subsequent save requests are done on the previous known filename.
  1541. :param param: Ignore.
  1542. :return: None
  1543. """
  1544. def on_success(app_obj, filename):
  1545. assert isinstance(app_obj, App)
  1546. app_obj.save_project(filename)
  1547. self.register_recent("project", filename)
  1548. app_obj.info("Project copy saved to: " + filename)
  1549. self.file_chooser_save_action(on_success)
  1550. def on_options_app2project(self, param):
  1551. """
  1552. Callback for Options->Transfer Options->App=>Project. Copies options
  1553. from application defaults to project defaults.
  1554. :param param: Ignored.
  1555. :return: None
  1556. """
  1557. self.options.update(self.defaults)
  1558. self.options2form() # Update UI
  1559. def on_options_project2app(self, param):
  1560. """
  1561. Callback for Options->Transfer Options->Project=>App. Copies options
  1562. from project defaults to application defaults.
  1563. :param param: Ignored.
  1564. :return: None
  1565. """
  1566. self.defaults.update(self.options)
  1567. self.options2form() # Update UI
  1568. def on_options_project2object(self, param):
  1569. """
  1570. Callback for Options->Transfer Options->Project=>Object. Copies options
  1571. from project defaults to the currently selected object.
  1572. :param param: Ignored.
  1573. :return: None
  1574. """
  1575. obj = self.get_current()
  1576. if obj is None:
  1577. self.info("WARNING: No object selected.")
  1578. return
  1579. for option in self.options:
  1580. if option.find(obj.kind + "_") == 0:
  1581. oname = option[len(obj.kind)+1:]
  1582. obj.options[oname] = self.options[option]
  1583. obj.to_form() # Update UI
  1584. def on_options_object2project(self, param):
  1585. """
  1586. Callback for Options->Transfer Options->Object=>Project. Copies options
  1587. from the currently selected object to project defaults.
  1588. :param param: Ignored.
  1589. :return: None
  1590. """
  1591. obj = self.get_current()
  1592. if obj is None:
  1593. self.info("WARNING: No object selected.")
  1594. return
  1595. obj.read_form()
  1596. for option in obj.options:
  1597. if option in ['name']: # TODO: Handle this better...
  1598. continue
  1599. self.options[obj.kind + "_" + option] = obj.options[option]
  1600. self.options2form() # Update UI
  1601. def on_options_object2app(self, param):
  1602. """
  1603. Callback for Options->Transfer Options->Object=>App. Copies options
  1604. from the currently selected object to application defaults.
  1605. :param param: Ignored.
  1606. :return: None
  1607. """
  1608. obj = self.get_current()
  1609. if obj is None:
  1610. self.info("WARNING: No object selected.")
  1611. return
  1612. obj.read_form()
  1613. for option in obj.options:
  1614. if option in ['name']: # TODO: Handle this better...
  1615. continue
  1616. self.defaults[obj.kind + "_" + option] = obj.options[option]
  1617. self.options2form() # Update UI
  1618. def on_options_app2object(self, param):
  1619. """
  1620. Callback for Options->Transfer Options->App=>Object. Copies options
  1621. from application defaults to the currently selected object.
  1622. :param param: Ignored.
  1623. :return: None
  1624. """
  1625. obj = self.get_current()
  1626. if obj is None:
  1627. self.info("WARNING: No object selected.")
  1628. return
  1629. for option in self.defaults:
  1630. if option.find(obj.kind + "_") == 0:
  1631. oname = option[len(obj.kind)+1:]
  1632. obj.options[oname] = self.defaults[option]
  1633. obj.to_form() # Update UI
  1634. def on_file_savedefaults(self, param):
  1635. """
  1636. Callback for menu item File->Save Defaults. Saves application default options
  1637. ``self.defaults`` to defaults.json.
  1638. :param param: Ignored.
  1639. :return: None
  1640. """
  1641. # Read options from file
  1642. try:
  1643. f = open("defaults.json")
  1644. options = f.read()
  1645. f.close()
  1646. except:
  1647. self.info("ERROR: Could not load defaults file.")
  1648. return
  1649. try:
  1650. defaults = json.loads(options)
  1651. except:
  1652. e = sys.exc_info()[0]
  1653. print e
  1654. self.info("ERROR: Failed to parse defaults file.")
  1655. return
  1656. # Update options
  1657. assert isinstance(defaults, dict)
  1658. defaults.update(self.defaults)
  1659. # Save update options
  1660. try:
  1661. f = open("defaults.json", "w")
  1662. json.dump(defaults, f)
  1663. f.close()
  1664. except:
  1665. self.info("ERROR: Failed to write defaults to file.")
  1666. return
  1667. self.info("Defaults saved.")
  1668. def on_options_combo_change(self, widget):
  1669. """
  1670. Called when the combo box to choose between application defaults and
  1671. project option changes value. The corresponding variables are
  1672. copied to the UI.
  1673. :param widget: The widget from which this was called. Ignore.
  1674. :return: None
  1675. """
  1676. #combo_sel = self.combo_options.get_active()
  1677. #print "Options --> ", combo_sel
  1678. self.options2form()
  1679. def on_options_update(self, widget):
  1680. """
  1681. Called whenever a value in the options/defaults form changes.
  1682. All values are updated. Can be inhibited by setting ``self.options_update_ignore = True``,
  1683. which may be necessary when updating the UI from code and not by the user.
  1684. :param widget: The widget from which this was called. Ignore.
  1685. :return: None
  1686. """
  1687. if self.options_update_ignore:
  1688. return
  1689. self.read_form()
  1690. def on_scale_object(self, widget):
  1691. """
  1692. Callback for request to change an objects geometry scale. The object
  1693. is re-scaled and replotted.
  1694. :param widget: Ignored.
  1695. :return: None
  1696. """
  1697. obj = self.get_current()
  1698. factor = self.get_eval("entry_eval_" + obj.kind + "_scalefactor")
  1699. obj.scale(factor)
  1700. obj.to_form()
  1701. self.on_update_plot(None)
  1702. def on_canvas_configure(self, widget, event):
  1703. """
  1704. Called whenever the canvas changes size. The axes are updated such
  1705. as to use the whole canvas.
  1706. :param widget: Ignored.
  1707. :param event: Ignored.
  1708. :return: None
  1709. """
  1710. self.plotcanvas.auto_adjust_axes()
  1711. def on_row_activated(self, widget, path, col):
  1712. """
  1713. Callback for selection activation (Enter or double-click) on the Project list.
  1714. Switches the notebook page to the object properties form. Calls
  1715. ``self.notebook.set_current_page(1)``.
  1716. :param widget: Ignored.
  1717. :param path: Ignored.
  1718. :param col: Ignored.
  1719. :return: None
  1720. """
  1721. self.notebook.set_current_page(1)
  1722. def on_generate_gerber_bounding_box(self, widget):
  1723. """
  1724. Callback for request from the Gerber form to generate a bounding box for the
  1725. geometry in the object. Creates a FlatCAMGeometry with the bounding box.
  1726. The box can have rounded corners if specified in the form.
  1727. :param widget: Ignored.
  1728. :return: None
  1729. """
  1730. # TODO: Use Gerber.get_bounding_box(...)
  1731. gerber = self.get_current()
  1732. gerber.read_form()
  1733. name = gerber.options["name"] + "_bbox"
  1734. def geo_init(geo_obj, app_obj):
  1735. assert isinstance(geo_obj, FlatCAMGeometry)
  1736. # Bounding box with rounded corners
  1737. bounding_box = gerber.solid_geometry.envelope.buffer(gerber.options["bboxmargin"])
  1738. if not gerber.options["bboxrounded"]: # Remove rounded corners
  1739. bounding_box = bounding_box.envelope
  1740. geo_obj.solid_geometry = bounding_box
  1741. self.new_object("geometry", name, geo_init)
  1742. def on_update_plot(self, widget):
  1743. """
  1744. Callback for button on form for all kinds of objects.
  1745. Re-plots the current object only.
  1746. :param widget: The widget from which this was called. Ignored.
  1747. :return: None
  1748. """
  1749. obj = self.get_current()
  1750. obj.read_form()
  1751. self.set_progress_bar(0.5, "Plotting...")
  1752. def thread_func(app_obj):
  1753. assert isinstance(app_obj, App)
  1754. obj.plot()
  1755. GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, "Idle"))
  1756. t = threading.Thread(target=thread_func, args=(self,))
  1757. t.daemon = True
  1758. t.start()
  1759. def on_generate_excellon_cncjob(self, widget):
  1760. """
  1761. Callback for button active/click on Excellon form to
  1762. create a CNC Job for the Excellon file.
  1763. :param widget: Ignored
  1764. :return: None
  1765. """
  1766. excellon = self.get_current()
  1767. excellon.read_form()
  1768. job_name = excellon.options["name"] + "_cnc"
  1769. # Object initialization function for app.new_object()
  1770. def job_init(job_obj, app_obj):
  1771. # excellon_ = self.get_current()
  1772. # assert isinstance(excellon_, FlatCAMExcellon)
  1773. assert isinstance(job_obj, FlatCAMCNCjob)
  1774. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job..."))
  1775. job_obj.z_cut = excellon.options["drillz"]
  1776. job_obj.z_move = excellon.options["travelz"]
  1777. job_obj.feedrate = excellon.options["feedrate"]
  1778. # There could be more than one drill size...
  1779. # job_obj.tooldia = # TODO: duplicate variable!
  1780. # job_obj.options["tooldia"] =
  1781. job_obj.generate_from_excellon_by_tool(excellon, excellon.options["toolselection"])
  1782. GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code..."))
  1783. job_obj.gcode_parse()
  1784. GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry..."))
  1785. job_obj.create_geometry()
  1786. GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting..."))
  1787. # To be run in separate thread
  1788. def job_thread(app_obj):
  1789. app_obj.new_object("cncjob", job_name, job_init)
  1790. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  1791. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  1792. # Start the thread
  1793. t = threading.Thread(target=job_thread, args=(self,))
  1794. t.daemon = True
  1795. t.start()
  1796. def on_excellon_tool_choose(self, widget):
  1797. """
  1798. Callback for button on Excellon form to open up a window for
  1799. selecting tools.
  1800. :param widget: The widget from which this was called.
  1801. :return: None
  1802. """
  1803. excellon = self.get_current()
  1804. assert isinstance(excellon, FlatCAMExcellon)
  1805. excellon.show_tool_chooser()
  1806. def on_entry_eval_activate(self, widget):
  1807. """
  1808. Called when an entry is activated (eg. by hitting enter) if
  1809. set to do so. Its text is eval()'d and set to the returned value.
  1810. The current object is updated.
  1811. :param widget:
  1812. :return:
  1813. """
  1814. self.on_eval_update(widget)
  1815. obj = self.get_current()
  1816. assert isinstance(obj, FlatCAMObj)
  1817. obj.read_form()
  1818. def on_gerber_generate_noncopper(self, widget):
  1819. """
  1820. Callback for button on Gerber form to create a geometry object
  1821. with polygons covering the area without copper or negative of the
  1822. Gerber.
  1823. :param widget: The widget from which this was called.
  1824. :return: None
  1825. """
  1826. gerb = self.get_current()
  1827. gerb.read_form()
  1828. name = gerb.options["name"] + "_noncopper"
  1829. def geo_init(geo_obj, app_obj):
  1830. assert isinstance(geo_obj, FlatCAMGeometry)
  1831. bounding_box = gerb.solid_geometry.envelope.buffer(gerb.options["noncoppermargin"])
  1832. if not gerb.options["noncopperrounded"]:
  1833. bounding_box = bounding_box.envelope
  1834. non_copper = bounding_box.difference(gerb.solid_geometry)
  1835. geo_obj.solid_geometry = non_copper
  1836. # TODO: Check for None
  1837. self.new_object("geometry", name, geo_init)
  1838. def on_gerber_generate_cutout(self, widget):
  1839. """
  1840. Callback for button on Gerber form to create geometry with lines
  1841. for cutting off the board.
  1842. :param widget: The widget from which this was called.
  1843. :return: None
  1844. """
  1845. gerb = self.get_current()
  1846. gerb.read_form()
  1847. name = gerb.options["name"] + "_cutout"
  1848. def geo_init(geo_obj, app_obj):
  1849. margin = gerb.options["cutoutmargin"] + gerb.options["cutouttooldia"]/2
  1850. gap_size = gerb.options["cutoutgapsize"] + gerb.options["cutouttooldia"]
  1851. minx, miny, maxx, maxy = gerb.bounds()
  1852. minx -= margin
  1853. maxx += margin
  1854. miny -= margin
  1855. maxy += margin
  1856. midx = 0.5 * (minx + maxx)
  1857. midy = 0.5 * (miny + maxy)
  1858. hgap = 0.5 * gap_size
  1859. pts = [[midx - hgap, maxy],
  1860. [minx, maxy],
  1861. [minx, midy + hgap],
  1862. [minx, midy - hgap],
  1863. [minx, miny],
  1864. [midx - hgap, miny],
  1865. [midx + hgap, miny],
  1866. [maxx, miny],
  1867. [maxx, midy - hgap],
  1868. [maxx, midy + hgap],
  1869. [maxx, maxy],
  1870. [midx + hgap, maxy]]
  1871. cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  1872. [pts[6], pts[7], pts[10], pts[11]]],
  1873. "lr": [[pts[9], pts[10], pts[1], pts[2]],
  1874. [pts[3], pts[4], pts[7], pts[8]]],
  1875. "4": [[pts[0], pts[1], pts[2]],
  1876. [pts[3], pts[4], pts[5]],
  1877. [pts[6], pts[7], pts[8]],
  1878. [pts[9], pts[10], pts[11]]]}
  1879. cuts = cases[app.get_radio_value({"rb_2tb": "tb", "rb_2lr": "lr", "rb_4": "4"})]
  1880. geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  1881. # TODO: Check for None
  1882. self.new_object("geometry", name, geo_init)
  1883. def on_eval_update(self, widget):
  1884. """
  1885. Modifies the content of a Gtk.Entry by running
  1886. eval() on its contents and puting it back as a
  1887. string.
  1888. :param widget: The widget from which this was called.
  1889. :return: None
  1890. """
  1891. # TODO: error handling here
  1892. widget.set_text(str(eval(widget.get_text())))
  1893. def on_generate_isolation(self, widget):
  1894. """
  1895. Callback for button on Gerber form to create isolation routing geometry.
  1896. :param widget: The widget from which this was called.
  1897. :return: None
  1898. """
  1899. gerb = self.get_current()
  1900. gerb.read_form()
  1901. dia = gerb.options["isotooldia"]
  1902. passes = int(gerb.options["isopasses"])
  1903. overlap = gerb.options["isooverlap"] * dia
  1904. for i in range(passes):
  1905. offset = (2*i + 1)/2.0 * dia - i*overlap
  1906. iso_name = gerb.options["name"] + "_iso%d" % (i+1)
  1907. # TODO: This is ugly. Create way to pass data into init function.
  1908. def iso_init(geo_obj, app_obj):
  1909. # Propagate options
  1910. geo_obj.options["cnctooldia"] = gerb.options["isotooldia"]
  1911. geo_obj.solid_geometry = gerb.isolation_geometry(offset)
  1912. app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
  1913. # TODO: Do something if this is None. Offer changing name?
  1914. self.new_object("geometry", iso_name, iso_init)
  1915. def on_generate_cncjob(self, widget):
  1916. """
  1917. Callback for button on geometry form to generate CNC job.
  1918. :param widget: The widget from which this was called.
  1919. :return: None
  1920. """
  1921. source_geo = self.get_current()
  1922. source_geo.read_form()
  1923. job_name = source_geo.options["name"] + "_cnc"
  1924. # Object initialization function for app.new_object()
  1925. # RUNNING ON SEPARATE THREAD!
  1926. def job_init(job_obj, app_obj):
  1927. assert isinstance(job_obj, FlatCAMCNCjob)
  1928. # Propagate options
  1929. job_obj.options["tooldia"] = source_geo.options["cnctooldia"]
  1930. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Creating CNC Job..."))
  1931. job_obj.z_cut = source_geo.options["cutz"]
  1932. job_obj.z_move = source_geo.options["travelz"]
  1933. job_obj.feedrate = source_geo.options["feedrate"]
  1934. GLib.idle_add(lambda: app_obj.set_progress_bar(0.4, "Analyzing Geometry..."))
  1935. # TODO: The tolerance should not be hard coded. Just for testing.
  1936. job_obj.generate_from_geometry(source_geo, tolerance=0.0005)
  1937. GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Parsing G-Code..."))
  1938. job_obj.gcode_parse()
  1939. # TODO: job_obj.create_geometry creates stuff that is not used.
  1940. #GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Creating New Geometry..."))
  1941. #job_obj.create_geometry()
  1942. GLib.idle_add(lambda: app_obj.set_progress_bar(0.8, "Plotting..."))
  1943. # To be run in separate thread
  1944. def job_thread(app_obj):
  1945. app_obj.new_object("cncjob", job_name, job_init)
  1946. GLib.idle_add(lambda: app_obj.info("CNCjob created: %s" % job_name))
  1947. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  1948. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  1949. # Start the thread
  1950. t = threading.Thread(target=job_thread, args=(self,))
  1951. t.daemon = True
  1952. t.start()
  1953. def on_generate_paintarea(self, widget):
  1954. """
  1955. Callback for button on geometry form.
  1956. Subscribes to the "Click on plot" event and continues
  1957. after the click. Finds the polygon containing
  1958. the clicked point and runs clear_poly() on it, resulting
  1959. in a new FlatCAMGeometry object.
  1960. :param widget: The widget from which this was called.
  1961. :return: None
  1962. """
  1963. self.info("Click inside the desired polygon.")
  1964. geo = self.get_current()
  1965. geo.read_form()
  1966. assert isinstance(geo, FlatCAMGeometry)
  1967. tooldia = geo.options["painttooldia"]
  1968. overlap = geo.options["paintoverlap"]
  1969. # To be called after clicking on the plot.
  1970. def doit(event):
  1971. self.plot_click_subscribers.pop("generate_paintarea")
  1972. self.info("")
  1973. point = [event.xdata, event.ydata]
  1974. poly = find_polygon(geo.solid_geometry, point)
  1975. # Initializes the new geometry object
  1976. def gen_paintarea(geo_obj, app_obj):
  1977. assert isinstance(geo_obj, FlatCAMGeometry)
  1978. assert isinstance(app_obj, App)
  1979. cp = clear_poly(poly.buffer(-geo.options["paintmargin"]), tooldia, overlap)
  1980. geo_obj.solid_geometry = cp
  1981. geo_obj.options["cnctooldia"] = tooldia
  1982. name = self.selected_item_name + "_paint"
  1983. self.new_object("geometry", name, gen_paintarea)
  1984. self.plot_click_subscribers["generate_paintarea"] = doit
  1985. def on_cncjob_exportgcode(self, widget):
  1986. """
  1987. Called from button on CNCjob form to save the G-Code from the object.
  1988. :param widget: The widget from which this was called.
  1989. :return: None
  1990. """
  1991. def on_success(app_obj, filename):
  1992. cncjob = app_obj.get_current()
  1993. f = open(filename, 'w')
  1994. f.write(cncjob.gcode)
  1995. f.close()
  1996. app_obj.info("Saved to: " + filename)
  1997. self.file_chooser_save_action(on_success)
  1998. def on_delete(self, widget):
  1999. """
  2000. Delete the currently selected FlatCAMObj.
  2001. :param widget: The widget from which this was called. Ignored.
  2002. :return: None
  2003. """
  2004. # Keep this for later
  2005. name = copy.copy(self.selected_item_name)
  2006. # Remove plot
  2007. self.plotcanvas.figure.delaxes(self.get_current().axes)
  2008. self.plotcanvas.auto_adjust_axes()
  2009. # Remove from dictionary
  2010. self.stuff.pop(self.selected_item_name)
  2011. # Update UI
  2012. self.build_list() # Update the items list
  2013. self.info("Object deleted: %s" % name)
  2014. def on_toolbar_replot(self, widget):
  2015. """
  2016. Callback for toolbar button. Re-plots all objects.
  2017. :param widget: The widget from which this was called.
  2018. :return: None
  2019. """
  2020. self.get_current().read_form()
  2021. self.plot_all()
  2022. def on_clear_plots(self, widget):
  2023. """
  2024. Callback for toolbar button. Clears all plots.
  2025. :param widget: The widget from which this was called.
  2026. :return: None
  2027. """
  2028. self.plotcanvas.clear()
  2029. def on_activate_name(self, entry):
  2030. """
  2031. Hitting 'Enter' after changing the name of an item
  2032. updates the item dictionary and re-builds the item list.
  2033. :param entry: The widget from which this was called.
  2034. :return: None
  2035. """
  2036. # Disconnect event listener
  2037. self.tree.get_selection().disconnect(self.signal_id)
  2038. new_name = entry.get_text() # Get from form
  2039. self.stuff[new_name] = self.stuff.pop(self.selected_item_name) # Update dictionary
  2040. self.stuff[new_name].options["name"] = new_name # update object
  2041. self.info('Name change: ' + self.selected_item_name + " to " + new_name)
  2042. self.selected_item_name = new_name # Update selection name
  2043. self.build_list() # Update the items list
  2044. # Reconnect event listener
  2045. self.signal_id = self.tree.get_selection().connect(
  2046. "changed", self.on_tree_selection_changed)
  2047. def on_tree_selection_changed(self, selection):
  2048. """
  2049. Callback for selection change in the project list. This changes
  2050. the currently selected FlatCAMObj.
  2051. :param selection: Selection associated to the project tree or list
  2052. :type selection: Gtk.TreeSelection
  2053. :return: None
  2054. """
  2055. print "DEBUG: on_tree_selection_change(): ",
  2056. model, treeiter = selection.get_selected()
  2057. if treeiter is not None:
  2058. # Save data for previous selection
  2059. obj = self.get_current()
  2060. if obj is not None:
  2061. obj.read_form()
  2062. print "DEBUG: You selected", model[treeiter][0]
  2063. self.selected_item_name = model[treeiter][0]
  2064. obj_new = self.get_current()
  2065. if obj_new is not None:
  2066. GLib.idle_add(lambda: obj_new.build_ui())
  2067. else:
  2068. print "DEBUG: Nothing selected"
  2069. self.selected_item_name = None
  2070. self.setup_component_editor()
  2071. def on_file_new(self, param):
  2072. """
  2073. Callback for menu item File->New. Returns the application to its
  2074. startup state.
  2075. :param param: Whatever is passed by the event. Ignore.
  2076. :return: None
  2077. """
  2078. # Remove everythong from memory
  2079. # Clear plot
  2080. self.plotcanvas.clear()
  2081. # Clear object editor
  2082. #self.setup_component_editor()
  2083. # Clear data
  2084. self.stuff = {}
  2085. # Clear list
  2086. #self.tree_select.unselect_all()
  2087. self.build_list()
  2088. # Clear project filename
  2089. self.project_filename = None
  2090. # Re-fresh project options
  2091. self.on_options_app2project(None)
  2092. def on_filequit(self, param):
  2093. """
  2094. Callback for menu item File->Quit. Closes the application.
  2095. :param param: Whatever is passed by the event. Ignore.
  2096. :return: None
  2097. """
  2098. self.window.destroy()
  2099. Gtk.main_quit()
  2100. def on_closewindow(self, param):
  2101. """
  2102. Callback for closing the main window.
  2103. :param param: Whatever is passed by the event. Ignore.
  2104. :return: None
  2105. """
  2106. self.window.destroy()
  2107. Gtk.main_quit()
  2108. def file_chooser_action(self, on_success):
  2109. """
  2110. Opens the file chooser and runs on_success on a separate thread
  2111. upon completion of valid file choice.
  2112. :param on_success: A function to run upon completion of a valid file
  2113. selection. Takes 2 parameters: The app instance and the filename.
  2114. Note that it is run on a separate thread, therefore it must take the
  2115. appropriate precautions when accessing shared resources.
  2116. :type on_success: func
  2117. :return: None
  2118. """
  2119. dialog = Gtk.FileChooserDialog("Please choose a file", self.window,
  2120. Gtk.FileChooserAction.OPEN,
  2121. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  2122. Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
  2123. response = dialog.run()
  2124. if response == Gtk.ResponseType.OK:
  2125. filename = dialog.get_filename()
  2126. dialog.destroy()
  2127. t = threading.Thread(target=on_success, args=(self, filename))
  2128. t.daemon = True
  2129. t.start()
  2130. #on_success(self, filename)
  2131. elif response == Gtk.ResponseType.CANCEL:
  2132. self.info("Open cancelled.") # print("Cancel clicked")
  2133. dialog.destroy()
  2134. def file_chooser_save_action(self, on_success):
  2135. """
  2136. Opens the file chooser and runs on_success upon completion of valid file choice.
  2137. :param on_success: A function to run upon selection of a filename. Takes 2
  2138. parameters: The instance of the application (App) and the chosen filename. This
  2139. gets run immediately in the same thread.
  2140. :return: None
  2141. """
  2142. dialog = Gtk.FileChooserDialog("Save file", self.window,
  2143. Gtk.FileChooserAction.SAVE,
  2144. (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
  2145. Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
  2146. dialog.set_current_name("Untitled")
  2147. response = dialog.run()
  2148. if response == Gtk.ResponseType.OK:
  2149. filename = dialog.get_filename()
  2150. dialog.destroy()
  2151. on_success(self, filename)
  2152. elif response == Gtk.ResponseType.CANCEL:
  2153. self.info("Save cancelled.") # print("Cancel clicked")
  2154. dialog.destroy()
  2155. def on_fileopengerber(self, param):
  2156. """
  2157. Callback for menu item File->Open Gerber. Defines a function that is then passed
  2158. to ``self.file_chooser_action()``. It requests the creation of a FlatCAMGerber object
  2159. and updates the progress bar throughout the process.
  2160. :param param: Ignore
  2161. :return: None
  2162. """
  2163. # IMPORTANT: on_success will run on a separate thread. Use
  2164. # GLib.idle_add(function, **kwargs) to launch actions that will
  2165. # updata the GUI.
  2166. def on_success(app_obj, filename):
  2167. assert isinstance(app_obj, App)
  2168. GLib.idle_add(lambda: app_obj.set_progress_bar(0.1, "Opening Gerber ..."))
  2169. def obj_init(gerber_obj, app_obj):
  2170. assert isinstance(gerber_obj, FlatCAMGerber)
  2171. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Parsing ..."))
  2172. gerber_obj.parse_file(filename)
  2173. GLib.idle_add(lambda: app_obj.set_progress_bar(0.5, "Creating Geometry ..."))
  2174. gerber_obj.create_geometry()
  2175. GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Plotting ..."))
  2176. name = filename.split('/')[-1].split('\\')[-1]
  2177. app_obj.new_object("gerber", name, obj_init)
  2178. self.register_recent("gerber", filename)
  2179. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  2180. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  2181. # on_success gets run on a separate thread
  2182. self.file_chooser_action(on_success)
  2183. def on_fileopenexcellon(self, param):
  2184. """
  2185. Callback for menu item File->Open Excellon. Defines a function that is then passed
  2186. to ``self.file_chooser_action()``. It requests the creation of a FlatCAMExcellon object
  2187. and updates the progress bar throughout the process.
  2188. :param param: Ignore
  2189. :return: None
  2190. """
  2191. # IMPORTANT: on_success will run on a separate thread. Use
  2192. # GLib.idle_add(function, **kwargs) to launch actions that will
  2193. # updata the GUI.
  2194. def on_success(app_obj, filename):
  2195. assert isinstance(app_obj, App)
  2196. GLib.idle_add(lambda: app_obj.set_progress_bar(0.1, "Opening Excellon ..."))
  2197. def obj_init(excellon_obj, app_obj):
  2198. GLib.idle_add(lambda: app_obj.set_progress_bar(0.2, "Parsing ..."))
  2199. excellon_obj.parse_file(filename)
  2200. excellon_obj.create_geometry()
  2201. GLib.idle_add(lambda: app_obj.set_progress_bar(0.6, "Plotting ..."))
  2202. name = filename.split('/')[-1].split('\\')[-1]
  2203. app_obj.new_object("excellon", name, obj_init)
  2204. self.register_recent("excellon", filename)
  2205. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  2206. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  2207. # on_success gets run on a separate thread
  2208. self.file_chooser_action(on_success)
  2209. def on_fileopengcode(self, param):
  2210. """
  2211. Callback for menu item File->Open G-Code. Defines a function that is then passed
  2212. to ``self.file_chooser_action()``. It requests the creation of a FlatCAMCNCjob object
  2213. and updates the progress bar throughout the process.
  2214. :param param: Ignore
  2215. :return: None
  2216. """
  2217. # IMPORTANT: on_success will run on a separate thread. Use
  2218. # GLib.idle_add(function, **kwargs) to launch actions that will
  2219. # updata the GUI.
  2220. def on_success(app_obj, filename):
  2221. assert isinstance(app_obj, App)
  2222. def obj_init(job_obj, app_obj_):
  2223. """
  2224. :type app_obj_: App
  2225. """
  2226. assert isinstance(app_obj_, App)
  2227. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.1, "Opening G-Code ..."))
  2228. f = open(filename)
  2229. gcode = f.read()
  2230. f.close()
  2231. job_obj.gcode = gcode
  2232. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.2, "Parsing ..."))
  2233. job_obj.gcode_parse()
  2234. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.6, "Creating geometry ..."))
  2235. job_obj.create_geometry()
  2236. GLib.idle_add(lambda: app_obj_.set_progress_bar(0.6, "Plotting ..."))
  2237. name = filename.split('/')[-1].split('\\')[-1]
  2238. app_obj.new_object("cncjob", name, obj_init)
  2239. self.register_recent("cncjob", filename)
  2240. GLib.idle_add(lambda: app_obj.set_progress_bar(1.0, "Done!"))
  2241. GLib.timeout_add_seconds(1, lambda: app_obj.set_progress_bar(0.0, ""))
  2242. # on_success gets run on a separate thread
  2243. self.file_chooser_action(on_success)
  2244. def on_mouse_move_over_plot(self, event):
  2245. """
  2246. Callback for the mouse motion event over the plot. This event is generated
  2247. by the Matplotlib backend and has been registered in ``self.__init__()``.
  2248. For details, see: http://matplotlib.org/users/event_handling.html
  2249. :param event: Contains information about the event.
  2250. :return: None
  2251. """
  2252. try: # May fail in case mouse not within axes
  2253. self.position_label.set_label("X: %.4f Y: %.4f" % (
  2254. event.xdata, event.ydata))
  2255. self.mouse = [event.xdata, event.ydata]
  2256. for subscriber in self.plot_mousemove_subscribers:
  2257. self.plot_mousemove_subscribers[subscriber](event)
  2258. except:
  2259. self.position_label.set_label("")
  2260. self.mouse = None
  2261. def on_click_over_plot(self, event):
  2262. """
  2263. Callback for the mouse click event over the plot. This event is generated
  2264. by the Matplotlib backend and has been registered in ``self.__init__()``.
  2265. For details, see: http://matplotlib.org/users/event_handling.html
  2266. Default actions are:
  2267. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  2268. :param event: Contains information about the event, like which button
  2269. was clicked, the pixel coordinates and the axes coordinates.
  2270. :return: None
  2271. """
  2272. # For key presses
  2273. self.plotcanvas.canvas.grab_focus()
  2274. try:
  2275. print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  2276. event.button, event.x, event.y, event.xdata, event.ydata)
  2277. # TODO: This custom subscription mechanism is probably not necessary.
  2278. for subscriber in self.plot_click_subscribers:
  2279. self.plot_click_subscribers[subscriber](event)
  2280. self.clipboard.set_text("(%.4f, %.4f)" % (event.xdata, event.ydata), -1)
  2281. except Exception, e:
  2282. print "Outside plot!"
  2283. def on_zoom_in(self, event):
  2284. """
  2285. Callback for zoom-in request. This can be either from the corresponding
  2286. toolbar button or the '3' key when the canvas is focused. Calls ``self.zoom()``.
  2287. :param event: Ignored.
  2288. :return: None
  2289. """
  2290. self.plotcanvas.zoom(1.5)
  2291. return
  2292. def on_zoom_out(self, event):
  2293. """
  2294. Callback for zoom-out request. This can be either from the corresponding
  2295. toolbar button or the '2' key when the canvas is focused. Calls ``self.zoom()``.
  2296. :param event: Ignored.
  2297. :return: None
  2298. """
  2299. self.plotcanvas.zoom(1 / 1.5)
  2300. def on_zoom_fit(self, event):
  2301. """
  2302. Callback for zoom-out request. This can be either from the corresponding
  2303. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  2304. with axes limits from the geometry bounds of all objects.
  2305. :param event: Ignored.
  2306. :return: None
  2307. """
  2308. xmin, ymin, xmax, ymax = get_bounds(self.stuff)
  2309. width = xmax - xmin
  2310. height = ymax - ymin
  2311. xmin -= 0.05 * width
  2312. xmax += 0.05 * width
  2313. ymin -= 0.05 * height
  2314. ymax += 0.05 * height
  2315. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  2316. def on_key_over_plot(self, event):
  2317. """
  2318. Callback for the key pressed event when the canvas is focused. Keyboard
  2319. shortcuts are handled here. So far, these are the shortcuts:
  2320. ========== ============================================
  2321. Key Action
  2322. ========== ============================================
  2323. '1' Zoom-fit. Fits the axes limits to the data.
  2324. '2' Zoom-out.
  2325. '3' Zoom-in.
  2326. 'm' Toggle on-off the measuring tool.
  2327. ========== ============================================
  2328. :param event: Ignored.
  2329. :return: None
  2330. """
  2331. if event.key == '1': # 1
  2332. self.on_zoom_fit(None)
  2333. return
  2334. if event.key == '2': # 2
  2335. self.plotcanvas.zoom(1 / 1.5, self.mouse)
  2336. return
  2337. if event.key == '3': # 3
  2338. self.plotcanvas.zoom(1.5, self.mouse)
  2339. return
  2340. if event.key == 'm':
  2341. if self.measure.toggle_active():
  2342. self.info("Measuring tool ON")
  2343. else:
  2344. self.info("Measuring tool OFF")
  2345. return
  2346. class BaseDraw:
  2347. def __init__(self, plotcanvas, name=None):
  2348. """
  2349. :param plotcanvas: The PlotCanvas where the drawing tool will operate.
  2350. :type plotcanvas: PlotCanvas
  2351. """
  2352. self.plotcanvas = plotcanvas
  2353. # Must have unique axes
  2354. charset = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"
  2355. self.name = name or [random.choice(charset) for i in range(20)]
  2356. self.axes = self.plotcanvas.new_axes(self.name)
  2357. class DrawingObject(BaseDraw):
  2358. def __init__(self, plotcanvas, name=None):
  2359. """
  2360. Possible objects are:
  2361. * Point
  2362. * Line
  2363. * Rectangle
  2364. * Circle
  2365. * Polygon
  2366. """
  2367. BaseDraw.__init__(self, plotcanvas)
  2368. self.properties = {}
  2369. def plot(self):
  2370. return
  2371. def update_plot(self):
  2372. self.axes.cla()
  2373. self.plot()
  2374. self.plotcanvas.auto_adjust_axes()
  2375. class DrawingPoint(DrawingObject):
  2376. def __init__(self, plotcanvas, name=None, coord=None):
  2377. DrawingObject.__init__(self, plotcanvas)
  2378. self.properties.update({
  2379. "coordinate": coord
  2380. })
  2381. def plot(self):
  2382. x, y = self.properties["coordinate"]
  2383. self.axes.plot(x, y, 'o')
  2384. class Measurement:
  2385. def __init__(self, container, axes, click_subscibers, move_subscribers, update=None):
  2386. self.update = update
  2387. self.container = container
  2388. self.frame = None
  2389. self.label = None
  2390. self.click_subscribers = click_subscibers
  2391. self.move_subscribers = move_subscribers
  2392. self.point1 = None
  2393. self.point2 = None
  2394. self.active = False
  2395. def toggle_active(self, *args):
  2396. if self.active: # Deactivate
  2397. self.active = False
  2398. self.move_subscribers.pop("meas")
  2399. self.click_subscribers.pop("meas")
  2400. self.container.remove(self.frame)
  2401. if self.update is not None:
  2402. self.update()
  2403. return False
  2404. else: # Activate
  2405. print "DEBUG: Activating Measurement Tool..."
  2406. self.active = True
  2407. self.click_subscribers["meas"] = self.on_click
  2408. self.move_subscribers["meas"] = self.on_move
  2409. self.frame = Gtk.Frame()
  2410. self.frame.set_margin_right(5)
  2411. self.frame.set_margin_top(3)
  2412. align = Gtk.Alignment()
  2413. align.set(0, 0.5, 0, 0)
  2414. align.set_padding(4, 4, 4, 4)
  2415. self.label = Gtk.Label()
  2416. self.label.set_label("Click on a reference point...")
  2417. abox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 10)
  2418. abox.pack_start(Gtk.Image.new_from_file('share/measure16.png'), False, False, 0)
  2419. abox.pack_start(self.label, False, False, 0)
  2420. align.add(abox)
  2421. self.frame.add(align)
  2422. self.container.pack_end(self.frame, False, True, 1)
  2423. self.frame.show_all()
  2424. return True
  2425. def on_move(self, event):
  2426. if self.point1 is None:
  2427. self.label.set_label("Click on a reference point...")
  2428. else:
  2429. dx = event.xdata - self.point1[0]
  2430. dy = event.ydata - self.point1[1]
  2431. d = sqrt(dx**2 + dy**2)
  2432. self.label.set_label("D = %.4f D(x) = %.4f D(y) = %.4f" % (d, dx, dy))
  2433. if self.update is not None:
  2434. self.update()
  2435. def on_click(self, event):
  2436. if self.point1 is None:
  2437. self.point1 = (event.xdata, event.ydata)
  2438. else:
  2439. self.point2 = copy.copy(self.point1)
  2440. self.point1 = (event.xdata, event.ydata)
  2441. self.on_move(event)
  2442. class PlotCanvas:
  2443. """
  2444. Class handling the plotting area in the application.
  2445. """
  2446. def __init__(self, container):
  2447. """
  2448. The constructor configures the Matplotlib figure that
  2449. will contain all plots, creates the base axes and connects
  2450. events to the plotting area.
  2451. :param container: The parent container in which to draw plots.
  2452. :rtype: PlotCanvas
  2453. """
  2454. # Options
  2455. self.x_margin = 15 # pixels
  2456. self.y_margin = 25 # Pixels
  2457. # Parent container
  2458. self.container = container
  2459. # Plots go onto a single matplotlib.figure
  2460. self.figure = Figure(dpi=50) # TODO: dpi needed?
  2461. self.figure.patch.set_visible(False)
  2462. # These axes show the ticks and grid. No plotting done here.
  2463. # New axes must have a label, otherwise mpl returns an existing one.
  2464. self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label="base", alpha=0.0)
  2465. self.axes.set_aspect(1)
  2466. self.axes.grid(True)
  2467. # The canvas is the top level container (Gtk.DrawingArea)
  2468. self.canvas = FigureCanvas(self.figure)
  2469. self.canvas.set_hexpand(1)
  2470. self.canvas.set_vexpand(1)
  2471. self.canvas.set_can_focus(True) # For key press
  2472. # Attach to parent
  2473. self.container.attach(self.canvas, 0, 0, 600, 400) # TODO: Height and width are num. columns??
  2474. # Events
  2475. self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)
  2476. self.canvas.connect('configure-event', self.auto_adjust_axes)
  2477. self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)
  2478. self.canvas.connect("scroll-event", self.on_scroll)
  2479. self.canvas.mpl_connect('key_press_event', self.on_key_down)
  2480. self.canvas.mpl_connect('key_release_event', self.on_key_up)
  2481. self.mouse = [0, 0]
  2482. self.key = None
  2483. def on_key_down(self, event):
  2484. """
  2485. :param event:
  2486. :return:
  2487. """
  2488. self.key = event.key
  2489. def on_key_up(self, event):
  2490. """
  2491. :param event:
  2492. :return:
  2493. """
  2494. self.key = None
  2495. def mpl_connect(self, event_name, callback):
  2496. """
  2497. Attach an event handler to the canvas through the Matplotlib interface.
  2498. :param event_name: Name of the event
  2499. :type event_name: str
  2500. :param callback: Function to call
  2501. :type callback: func
  2502. :return: Nothing
  2503. """
  2504. self.canvas.mpl_connect(event_name, callback)
  2505. def connect(self, event_name, callback):
  2506. """
  2507. Attach an event handler to the canvas through the native GTK interface.
  2508. :param event_name: Name of the event
  2509. :type event_name: str
  2510. :param callback: Function to call
  2511. :type callback: function
  2512. :return: Nothing
  2513. """
  2514. self.canvas.connect(event_name, callback)
  2515. def clear(self):
  2516. """
  2517. Clears axes and figure.
  2518. :return: None
  2519. """
  2520. # Clear
  2521. self.axes.cla()
  2522. self.figure.clf()
  2523. # Re-build
  2524. self.figure.add_axes(self.axes)
  2525. self.axes.set_aspect(1)
  2526. self.axes.grid(True)
  2527. # Re-draw
  2528. self.canvas.queue_draw()
  2529. def adjust_axes(self, xmin, ymin, xmax, ymax):
  2530. """
  2531. Adjusts all axes while maintaining the use of the whole canvas
  2532. and an aspect ratio to 1:1 between x and y axes. The parameters are an original
  2533. request that will be modified to fit these restrictions.
  2534. :param xmin: Requested minimum value for the X axis.
  2535. :type xmin: float
  2536. :param ymin: Requested minimum value for the Y axis.
  2537. :type ymin: float
  2538. :param xmax: Requested maximum value for the X axis.
  2539. :type xmax: float
  2540. :param ymax: Requested maximum value for the Y axis.
  2541. :type ymax: float
  2542. :return: None
  2543. """
  2544. width = xmax - xmin
  2545. height = ymax - ymin
  2546. try:
  2547. r = width / height
  2548. except:
  2549. print "ERROR: Height is", height
  2550. return
  2551. canvas_w, canvas_h = self.canvas.get_width_height()
  2552. canvas_r = float(canvas_w) / canvas_h
  2553. x_ratio = float(self.x_margin) / canvas_w
  2554. y_ratio = float(self.y_margin) / canvas_h
  2555. if r > canvas_r:
  2556. ycenter = (ymin + ymax) / 2.0
  2557. newheight = height * r / canvas_r
  2558. ymin = ycenter - newheight / 2.0
  2559. ymax = ycenter + newheight / 2.0
  2560. else:
  2561. xcenter = (xmax + ymin) / 2.0
  2562. newwidth = width * canvas_r / r
  2563. xmin = xcenter - newwidth / 2.0
  2564. xmax = xcenter + newwidth / 2.0
  2565. # Adjust axes
  2566. for ax in self.figure.get_axes():
  2567. if ax._label != 'base':
  2568. ax.set_frame_on(False) # No frame
  2569. ax.set_xticks([]) # No tick
  2570. ax.set_yticks([]) # No ticks
  2571. ax.patch.set_visible(False) # No background
  2572. ax.set_aspect(1)
  2573. ax.set_xlim((xmin, xmax))
  2574. ax.set_ylim((ymin, ymax))
  2575. ax.set_position([x_ratio, y_ratio, 1 - 2 * x_ratio, 1 - 2 * y_ratio])
  2576. # Re-draw
  2577. self.canvas.queue_draw()
  2578. def auto_adjust_axes(self, *args):
  2579. """
  2580. Calls ``adjust_axes()`` using the extents of the base axes.
  2581. :rtype : None
  2582. :return: None
  2583. """
  2584. xmin, xmax = self.axes.get_xlim()
  2585. ymin, ymax = self.axes.get_ylim()
  2586. self.adjust_axes(xmin, ymin, xmax, ymax)
  2587. def zoom(self, factor, center=None):
  2588. """
  2589. Zooms the plot by factor around a given
  2590. center point. Takes care of re-drawing.
  2591. :param factor: Number by which to scale the plot.
  2592. :type factor: float
  2593. :param center: Coordinates [x, y] of the point around which to scale the plot.
  2594. :type center: list
  2595. :return: None
  2596. """
  2597. xmin, xmax = self.axes.get_xlim()
  2598. ymin, ymax = self.axes.get_ylim()
  2599. width = xmax - xmin
  2600. height = ymax - ymin
  2601. if center is None or center == [None, None]:
  2602. center = [(xmin + xmax) / 2.0, (ymin + ymax) / 2.0]
  2603. # For keeping the point at the pointer location
  2604. relx = (xmax - center[0]) / width
  2605. rely = (ymax - center[1]) / height
  2606. new_width = width / factor
  2607. new_height = height / factor
  2608. xmin = center[0] - new_width * (1 - relx)
  2609. xmax = center[0] + new_width * relx
  2610. ymin = center[1] - new_height * (1 - rely)
  2611. ymax = center[1] + new_height * rely
  2612. # Adjust axes
  2613. for ax in self.figure.get_axes():
  2614. ax.set_xlim((xmin, xmax))
  2615. ax.set_ylim((ymin, ymax))
  2616. # Re-draw
  2617. self.canvas.queue_draw()
  2618. def pan(self, x, y):
  2619. xmin, xmax = self.axes.get_xlim()
  2620. ymin, ymax = self.axes.get_ylim()
  2621. width = xmax - xmin
  2622. height = ymax - ymin
  2623. # Adjust axes
  2624. for ax in self.figure.get_axes():
  2625. ax.set_xlim((xmin + x*width, xmax + x*width))
  2626. ax.set_ylim((ymin + y*height, ymax + y*height))
  2627. # Re-draw
  2628. self.canvas.queue_draw()
  2629. def new_axes(self, name):
  2630. """
  2631. Creates and returns an Axes object attached to this object's Figure.
  2632. :param name: Unique label for the axes.
  2633. :return: Axes attached to the figure.
  2634. :rtype: Axes
  2635. """
  2636. return self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=name)
  2637. # def plot_axes(self, axes):
  2638. #
  2639. # if axes not in self.figure.axes:
  2640. # self.figure.add_axes(axes)
  2641. #
  2642. # # Basic configuration
  2643. # axes.set_frame_on(False) # No frame
  2644. # axes.set_xticks([]) # No tick
  2645. # axes.set_yticks([]) # No ticks
  2646. # axes.patch.set_visible(False) # No background
  2647. # axes.set_aspect(1)
  2648. #
  2649. # # Adjust limits
  2650. # self.auto_adjust_axes()
  2651. def on_scroll(self, canvas, event):
  2652. """
  2653. Scroll event handler.
  2654. :param canvas: The widget generating the event. Ignored.
  2655. :param event: Event object containing the event information.
  2656. :return: None
  2657. """
  2658. z, direction = event.get_scroll_direction()
  2659. if self.key is None:
  2660. if direction is Gdk.ScrollDirection.UP:
  2661. self.zoom(1.5, self.mouse)
  2662. else:
  2663. self.zoom(1/1.5, self.mouse)
  2664. return
  2665. if self.key == 'shift':
  2666. if direction is Gdk.ScrollDirection.UP:
  2667. self.pan(0.3, 0)
  2668. else:
  2669. self.pan(-0.3, 0)
  2670. return
  2671. if self.key == 'ctrl+control':
  2672. if direction is Gdk.ScrollDirection.UP:
  2673. self.pan(0, 0.3)
  2674. else:
  2675. self.pan(0, -0.3)
  2676. return
  2677. def on_mouse_move(self, event):
  2678. """
  2679. Mouse movement event hadler.
  2680. :param event: Contains information about the event.
  2681. :return: None
  2682. """
  2683. self.mouse = [event.xdata, event.ydata]
  2684. app = App()
  2685. Gtk.main()