FlatCAMApp.py 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009
  1. import sys
  2. import urllib
  3. import getopt
  4. import random
  5. import logging
  6. import simplejson as json
  7. import re
  8. import webbrowser
  9. import os
  10. import Tkinter
  11. from PyQt4 import QtCore
  12. import time # Just used for debugging. Double check before removing.
  13. from xml.dom.minidom import parseString as parse_xml_string
  14. from contextlib import contextmanager
  15. ########################################
  16. ## Imports part of FlatCAM ##
  17. ########################################
  18. from FlatCAMWorker import Worker
  19. from ObjectCollection import *
  20. from FlatCAMObj import *
  21. from PlotCanvas import *
  22. from FlatCAMGUI import *
  23. from FlatCAMCommon import LoudDict
  24. from FlatCAMShell import FCShell
  25. from FlatCAMDraw import FlatCAMDraw
  26. from FlatCAMProcess import *
  27. from MeasurementTool import Measurement
  28. from DblSidedTool import DblSidedTool
  29. ########################################
  30. ## App ##
  31. ########################################
  32. class App(QtCore.QObject):
  33. """
  34. The main application class. The constructor starts the GUI.
  35. """
  36. ## Get Cmd Line Options
  37. cmd_line_shellfile = ''
  38. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  39. try:
  40. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", "shellfile=")
  41. except getopt.GetoptError:
  42. print cmd_line_help
  43. sys.exit(2)
  44. for opt, arg in cmd_line_options:
  45. if opt == '-h':
  46. print cmd_line_help
  47. sys.exit()
  48. elif opt == '--shellfile':
  49. cmd_line_shellfile = arg
  50. ## Logging ##
  51. log = logging.getLogger('base')
  52. log.setLevel(logging.DEBUG)
  53. # log.setLevel(logging.WARNING)
  54. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  55. handler = logging.StreamHandler()
  56. handler.setFormatter(formatter)
  57. log.addHandler(handler)
  58. ## Version
  59. version = 8.4
  60. version_date = "2015/10"
  61. ## URL for update checks and statistics
  62. version_url = "http://flatcam.org/version"
  63. ## App URL
  64. app_url = "http://flatcam.org"
  65. ## Manual URL
  66. manual_url = "http://flatcam.org/manual/index.html"
  67. ##################
  68. ## Signals ##
  69. ##################
  70. # Inform the user
  71. # Handled by:
  72. # * App.info() --> Print on the status bar
  73. inform = QtCore.pyqtSignal(str)
  74. # General purpose background task
  75. worker_task = QtCore.pyqtSignal(dict)
  76. # File opened
  77. # Handled by:
  78. # * register_folder()
  79. # * register_recent()
  80. file_opened = QtCore.pyqtSignal(str, str) # File type and filename
  81. progress = QtCore.pyqtSignal(int) # Percentage of progress
  82. plots_updated = QtCore.pyqtSignal()
  83. # Emitted by new_object() and passes the new object as argument.
  84. # on_object_created() adds the object to the collection,
  85. # and emits new_object_available.
  86. object_created = QtCore.pyqtSignal(object)
  87. # Emitted when a new object has been added to the collection
  88. # and is ready to be used.
  89. new_object_available = QtCore.pyqtSignal(object)
  90. message = QtCore.pyqtSignal(str, str, str)
  91. # Emitted when an unhandled exception happens
  92. # in the worker task.
  93. thread_exception = QtCore.pyqtSignal(object)
  94. def __init__(self, user_defaults=True, post_gui=None):
  95. """
  96. Starts the application.
  97. :return: app
  98. :rtype: App
  99. """
  100. App.log.info("FlatCAM Starting...")
  101. ###################
  102. ### OS-specific ###
  103. ###################
  104. if sys.platform == 'win32':
  105. from win32com.shell import shell, shellcon
  106. App.log.debug("Win32!")
  107. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  108. '/FlatCAM'
  109. self.os = 'windows'
  110. else: # Linux/Unix/MacOS
  111. self.data_path = os.path.expanduser('~') + \
  112. '/.FlatCAM'
  113. self.os = 'unix'
  114. ###############################
  115. ### Setup folders and files ###
  116. ###############################
  117. if not os.path.exists(self.data_path):
  118. os.makedirs(self.data_path)
  119. App.log.debug('Created data folder: ' + self.data_path)
  120. try:
  121. f = open(self.data_path + '/defaults.json')
  122. f.close()
  123. except IOError:
  124. App.log.debug('Creating empty defaults.json')
  125. f = open(self.data_path + '/defaults.json', 'w')
  126. json.dump({}, f)
  127. f.close()
  128. try:
  129. f = open(self.data_path + '/recent.json')
  130. f.close()
  131. except IOError:
  132. App.log.debug('Creating empty recent.json')
  133. f = open(self.data_path + '/recent.json', 'w')
  134. json.dump([], f)
  135. f.close()
  136. # Application directory. Chdir to it. Otherwise, trying to load
  137. # GUI icons will fail as thir path is relative.
  138. # This will fail under cx_freeze ...
  139. self.app_home = os.path.dirname(os.path.realpath(__file__))
  140. App.log.debug("Application path is " + self.app_home)
  141. App.log.debug("Started in " + os.getcwd())
  142. os.chdir(self.app_home)
  143. ####################
  144. ## Initialize GUI ##
  145. ####################
  146. QtCore.QObject.__init__(self)
  147. self.ui = FlatCAMGUI(self.version)
  148. self.connect(self.ui,
  149. QtCore.SIGNAL("geomUpdate(int, int, int, int)"),
  150. self.save_geometry)
  151. #### Plot Area ####
  152. # self.plotcanvas = PlotCanvas(self.ui.splitter)
  153. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  154. self.plotcanvas.mpl_connect('button_press_event', self.on_click_over_plot)
  155. self.plotcanvas.mpl_connect('motion_notify_event', self.on_mouse_move_over_plot)
  156. self.plotcanvas.mpl_connect('key_press_event', self.on_key_over_plot)
  157. self.ui.splitter.setStretchFactor(1, 2)
  158. ##############
  159. #### Data ####
  160. ##############
  161. self.recent = []
  162. self.clipboard = QtGui.QApplication.clipboard()
  163. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  164. self.project_filename = None
  165. self.toggle_units_ignore = False
  166. self.defaults_form = GlobalOptionsUI()
  167. self.defaults_form_fields = {
  168. "units": self.defaults_form.units_radio,
  169. "gerber_plot": self.defaults_form.gerber_group.plot_cb,
  170. "gerber_solid": self.defaults_form.gerber_group.solid_cb,
  171. "gerber_multicolored": self.defaults_form.gerber_group.multicolored_cb,
  172. "gerber_isotooldia": self.defaults_form.gerber_group.iso_tool_dia_entry,
  173. "gerber_isopasses": self.defaults_form.gerber_group.iso_width_entry,
  174. "gerber_isooverlap": self.defaults_form.gerber_group.iso_overlap_entry,
  175. "gerber_combine_passes": self.defaults_form.gerber_group.combine_passes_cb,
  176. "gerber_cutouttooldia": self.defaults_form.gerber_group.cutout_tooldia_entry,
  177. "gerber_cutoutmargin": self.defaults_form.gerber_group.cutout_margin_entry,
  178. "gerber_cutoutgapsize": self.defaults_form.gerber_group.cutout_gap_entry,
  179. "gerber_gaps": self.defaults_form.gerber_group.gaps_radio,
  180. "gerber_noncoppermargin": self.defaults_form.gerber_group.noncopper_margin_entry,
  181. "gerber_noncopperrounded": self.defaults_form.gerber_group.noncopper_rounded_cb,
  182. "gerber_bboxmargin": self.defaults_form.gerber_group.bbmargin_entry,
  183. "gerber_bboxrounded": self.defaults_form.gerber_group.bbrounded_cb,
  184. "excellon_plot": self.defaults_form.excellon_group.plot_cb,
  185. "excellon_solid": self.defaults_form.excellon_group.solid_cb,
  186. "excellon_drillz": self.defaults_form.excellon_group.cutz_entry,
  187. "excellon_travelz": self.defaults_form.excellon_group.travelz_entry,
  188. "excellon_feedrate": self.defaults_form.excellon_group.feedrate_entry,
  189. "excellon_spindlespeed": self.defaults_form.excellon_group.spindlespeed_entry,
  190. "excellon_toolchangez": self.defaults_form.excellon_group.toolchangez_entry,
  191. "geometry_plot": self.defaults_form.geometry_group.plot_cb,
  192. "geometry_cutz": self.defaults_form.geometry_group.cutz_entry,
  193. "geometry_travelz": self.defaults_form.geometry_group.travelz_entry,
  194. "geometry_feedrate": self.defaults_form.geometry_group.cncfeedrate_entry,
  195. "geometry_cnctooldia": self.defaults_form.geometry_group.cnctooldia_entry,
  196. "geometry_painttooldia": self.defaults_form.geometry_group.painttooldia_entry,
  197. "geometry_spindlespeed": self.defaults_form.geometry_group.cncspindlespeed_entry,
  198. "geometry_paintoverlap": self.defaults_form.geometry_group.paintoverlap_entry,
  199. "geometry_paintmargin": self.defaults_form.geometry_group.paintmargin_entry,
  200. "cncjob_plot": self.defaults_form.cncjob_group.plot_cb,
  201. "cncjob_tooldia": self.defaults_form.cncjob_group.tooldia_entry,
  202. "cncjob_prepend": self.defaults_form.cncjob_group.prepend_text,
  203. "cncjob_append": self.defaults_form.cncjob_group.append_text
  204. }
  205. self.defaults = LoudDict()
  206. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  207. self.defaults.update({
  208. "serial": 0,
  209. "stats": {},
  210. "units": "IN",
  211. "gerber_plot": True,
  212. "gerber_solid": True,
  213. "gerber_multicolored": False,
  214. "gerber_isotooldia": 0.016,
  215. "gerber_isopasses": 1,
  216. "gerber_isooverlap": 0.15,
  217. "gerber_cutouttooldia": 0.07,
  218. "gerber_cutoutmargin": 0.1,
  219. "gerber_cutoutgapsize": 0.15,
  220. "gerber_gaps": "4",
  221. "gerber_noncoppermargin": 0.0,
  222. "gerber_noncopperrounded": False,
  223. "gerber_bboxmargin": 0.0,
  224. "gerber_bboxrounded": False,
  225. "excellon_plot": True,
  226. "excellon_solid": False,
  227. "excellon_drillz": -0.1,
  228. "excellon_travelz": 0.1,
  229. "excellon_feedrate": 3.0,
  230. "excellon_spindlespeed": None,
  231. "excellon_toolchangez": 1.0,
  232. "geometry_plot": True,
  233. "geometry_cutz": -0.002,
  234. "geometry_travelz": 0.1,
  235. "geometry_feedrate": 3.0,
  236. "geometry_cnctooldia": 0.016,
  237. "geometry_spindlespeed": None,
  238. "geometry_painttooldia": 0.07,
  239. "geometry_paintoverlap": 0.15,
  240. "geometry_paintmargin": 0.0,
  241. "cncjob_plot": True,
  242. "cncjob_tooldia": 0.016,
  243. "cncjob_prepend": "",
  244. "cncjob_append": "",
  245. # Persistence
  246. "last_folder": None,
  247. # Default window geometry
  248. "def_win_x": 100,
  249. "def_win_y": 100,
  250. "def_win_w": 1024,
  251. "def_win_h": 650,
  252. # Constants...
  253. "defaults_save_period_ms": 20000, # Time between default saves.
  254. "shell_shape": [500, 300], # Shape of the shell in pixels.
  255. "shell_at_startup": False, # Show the shell at startup.
  256. "recent_limit": 10, # Max. items in recent list.
  257. "fit_key": '1',
  258. "zoom_out_key": '2',
  259. "zoom_in_key": '3',
  260. "zoom_ratio": 1.5,
  261. "point_clipboard_format": "(%.4f, %.4f)",
  262. "zdownrate": None,
  263. "excellon_zeros": "L",
  264. "gerber_use_buffer_for_union": True,
  265. "cncjob_coordinate_format": "X%.4fY%.4f"
  266. })
  267. ###############################
  268. ### Load defaults from file ###
  269. if user_defaults:
  270. self.load_defaults()
  271. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  272. if self.defaults['serial'] == 0 or len(str(self.defaults['serial'])) < 10:
  273. self.defaults['serial'] = ''.join([random.choice(chars) for i in range(20)])
  274. self.save_defaults(silent=True)
  275. self.propagate_defaults()
  276. self.restore_main_win_geom()
  277. def auto_save_defaults():
  278. try:
  279. self.save_defaults(silent=True)
  280. finally:
  281. QtCore.QTimer.singleShot(self.defaults["defaults_save_period_ms"], auto_save_defaults)
  282. if user_defaults:
  283. QtCore.QTimer.singleShot(self.defaults["defaults_save_period_ms"], auto_save_defaults)
  284. self.options_form = GlobalOptionsUI()
  285. self.options_form_fields = {
  286. "units": self.options_form.units_radio,
  287. "gerber_plot": self.options_form.gerber_group.plot_cb,
  288. "gerber_solid": self.options_form.gerber_group.solid_cb,
  289. "gerber_multicolored": self.options_form.gerber_group.multicolored_cb,
  290. "gerber_isotooldia": self.options_form.gerber_group.iso_tool_dia_entry,
  291. "gerber_isopasses": self.options_form.gerber_group.iso_width_entry,
  292. "gerber_isooverlap": self.options_form.gerber_group.iso_overlap_entry,
  293. "gerber_combine_passes": self.options_form.gerber_group.combine_passes_cb,
  294. "gerber_cutouttooldia": self.options_form.gerber_group.cutout_tooldia_entry,
  295. "gerber_cutoutmargin": self.options_form.gerber_group.cutout_margin_entry,
  296. "gerber_cutoutgapsize": self.options_form.gerber_group.cutout_gap_entry,
  297. "gerber_gaps": self.options_form.gerber_group.gaps_radio,
  298. "gerber_noncoppermargin": self.options_form.gerber_group.noncopper_margin_entry,
  299. "gerber_noncopperrounded": self.options_form.gerber_group.noncopper_rounded_cb,
  300. "gerber_bboxmargin": self.options_form.gerber_group.bbmargin_entry,
  301. "gerber_bboxrounded": self.options_form.gerber_group.bbrounded_cb,
  302. "excellon_plot": self.options_form.excellon_group.plot_cb,
  303. "excellon_solid": self.options_form.excellon_group.solid_cb,
  304. "excellon_drillz": self.options_form.excellon_group.cutz_entry,
  305. "excellon_travelz": self.options_form.excellon_group.travelz_entry,
  306. "excellon_feedrate": self.options_form.excellon_group.feedrate_entry,
  307. "excellon_spindlespeed": self.options_form.excellon_group.spindlespeed_entry,
  308. "excellon_toolchangez": self.options_form.excellon_group.toolchangez_entry,
  309. "geometry_plot": self.options_form.geometry_group.plot_cb,
  310. "geometry_cutz": self.options_form.geometry_group.cutz_entry,
  311. "geometry_travelz": self.options_form.geometry_group.travelz_entry,
  312. "geometry_feedrate": self.options_form.geometry_group.cncfeedrate_entry,
  313. "geometry_spindlespeed": self.options_form.geometry_group.cncspindlespeed_entry,
  314. "geometry_cnctooldia": self.options_form.geometry_group.cnctooldia_entry,
  315. "geometry_painttooldia": self.options_form.geometry_group.painttooldia_entry,
  316. "geometry_paintoverlap": self.options_form.geometry_group.paintoverlap_entry,
  317. "geometry_paintmargin": self.options_form.geometry_group.paintmargin_entry,
  318. "cncjob_plot": self.options_form.cncjob_group.plot_cb,
  319. "cncjob_tooldia": self.options_form.cncjob_group.tooldia_entry,
  320. "cncjob_prepend": self.options_form.cncjob_group.prepend_text,
  321. "cncjob_append": self.options_form.cncjob_group.append_text
  322. }
  323. self.options = LoudDict()
  324. self.options.set_change_callback(self.on_options_dict_change)
  325. self.options.update({
  326. "units": "IN",
  327. "gerber_plot": True,
  328. "gerber_solid": True,
  329. "gerber_multicolored": False,
  330. "gerber_isotooldia": 0.016,
  331. "gerber_isopasses": 1,
  332. "gerber_isooverlap": 0.15,
  333. "gerber_combine_passes": True,
  334. "gerber_cutouttooldia": 0.07,
  335. "gerber_cutoutmargin": 0.1,
  336. "gerber_cutoutgapsize": 0.15,
  337. "gerber_gaps": "4",
  338. "gerber_noncoppermargin": 0.0,
  339. "gerber_noncopperrounded": False,
  340. "gerber_bboxmargin": 0.0,
  341. "gerber_bboxrounded": False,
  342. "excellon_plot": True,
  343. "excellon_solid": False,
  344. "excellon_drillz": -0.1,
  345. "excellon_travelz": 0.1,
  346. "excellon_feedrate": 3.0,
  347. "excellon_spindlespeed": None,
  348. "excellon_toolchangez": 1.0,
  349. "geometry_plot": True,
  350. "geometry_cutz": -0.002,
  351. "geometry_travelz": 0.1,
  352. "geometry_feedrate": 3.0,
  353. "geometry_spindlespeed": None,
  354. "geometry_cnctooldia": 0.016,
  355. "geometry_painttooldia": 0.07,
  356. "geometry_paintoverlap": 0.15,
  357. "geometry_paintmargin": 0.0,
  358. "cncjob_plot": True,
  359. "cncjob_tooldia": 0.016,
  360. "cncjob_prepend": "",
  361. "cncjob_append": ""
  362. })
  363. self.options.update(self.defaults) # Copy app defaults to project options
  364. #self.options_write_form()
  365. self.on_options_combo_change(0) # Will show the initial form
  366. self.collection = ObjectCollection()
  367. self.ui.project_tab_layout.addWidget(self.collection.view)
  368. #### End of Data ####
  369. #### Worker ####
  370. App.log.info("Starting Worker...")
  371. self.worker = Worker(self)
  372. self.thr1 = QtCore.QThread()
  373. self.worker.moveToThread(self.thr1)
  374. self.connect(self.thr1, QtCore.SIGNAL("started()"), self.worker.run)
  375. self.thr1.start()
  376. #### Check for updates ####
  377. # Separate thread (Not worker)
  378. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  379. self.worker2 = Worker(self, name="worker2")
  380. self.thr2 = QtCore.QThread()
  381. self.worker2.moveToThread(self.thr2)
  382. self.connect(self.thr2, QtCore.SIGNAL("started()"), self.worker2.run)
  383. self.connect(self.thr2, QtCore.SIGNAL("started()"),
  384. lambda: self.worker_task.emit({'fcn': self.version_check,
  385. 'params': [],
  386. 'worker_name': "worker2"}))
  387. self.thr2.start()
  388. ### Signal handling ###
  389. ## Custom signals
  390. self.inform.connect(self.info)
  391. self.message.connect(self.message_dialog)
  392. self.progress.connect(self.set_progress_bar)
  393. self.object_created.connect(self.on_object_created)
  394. self.plots_updated.connect(self.on_plots_updated)
  395. self.file_opened.connect(self.register_recent)
  396. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  397. ## Standard signals
  398. # Menu
  399. self.ui.menufilenew.triggered.connect(self.on_file_new)
  400. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  401. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  402. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  403. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  404. self.ui.menufileimportsvg.triggered.connect(self.on_file_importsvg)
  405. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  406. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  407. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  408. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  409. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  410. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'New Geometry', lambda x, y: None))
  411. self.ui.menueditedit.triggered.connect(self.edit_geometry)
  412. self.ui.menueditok.triggered.connect(self.editor2geometry)
  413. self.ui.menueditjoin.triggered.connect(self.on_edit_join)
  414. self.ui.menueditdelete.triggered.connect(self.on_delete)
  415. self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  416. self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  417. self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  418. self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  419. self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  420. self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  421. self.ui.menuviewdisableall.triggered.connect(self.disable_plots)
  422. self.ui.menuviewdisableother.triggered.connect(lambda: self.disable_plots(except_current=True))
  423. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  424. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  425. self.ui.menuhelp_about.triggered.connect(self.on_about)
  426. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  427. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  428. # Toolbar
  429. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  430. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  431. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  432. self.ui.clear_plot_btn.triggered.connect(self.plotcanvas.clear)
  433. self.ui.replot_btn.triggered.connect(self.on_toolbar_replot)
  434. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'New Geometry', lambda x, y: None))
  435. self.ui.editgeo_btn.triggered.connect(self.edit_geometry)
  436. self.ui.updategeo_btn.triggered.connect(self.editor2geometry)
  437. self.ui.delete_btn.triggered.connect(self.on_delete)
  438. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  439. # Object list
  440. self.collection.view.activated.connect(self.on_row_activated)
  441. # Options
  442. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  443. self.options_form.units_radio.group_toggle_fn = self.on_toggle_units
  444. ####################
  445. ### Other setups ###
  446. ####################
  447. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  448. self.setup_obj_classes()
  449. self.setup_recent_items()
  450. self.setup_component_editor()
  451. #########################
  452. ### Tools and Plugins ###
  453. #########################
  454. self.dblsidedtool = DblSidedTool(self)
  455. self.dblsidedtool.install()
  456. self.measeurement_tool = Measurement(self)
  457. self.measeurement_tool.install()
  458. self.draw = FlatCAMDraw(self, disabled=True)
  459. #############
  460. ### Shell ###
  461. #############
  462. # TODO: Move this to its own class
  463. self.shell = FCShell(self)
  464. self.shell.setWindowIcon(self.ui.app_icon)
  465. self.shell.setWindowTitle("FlatCAM Shell")
  466. self.shell.resize(*self.defaults["shell_shape"])
  467. self.shell.append_output("FlatCAM %s\n(c) 2014-2015 Juan Pablo Caram\n\n" % self.version)
  468. self.shell.append_output("Type help to get started.\n\n")
  469. self.tcl = Tkinter.Tcl()
  470. self.setup_shell()
  471. self.ui.shell_dock = QtGui.QDockWidget("FlatCAM TCL Shell")
  472. self.ui.shell_dock.setWidget(self.shell)
  473. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  474. self.ui.shell_dock.setFeatures(QtGui.QDockWidget.DockWidgetMovable |
  475. QtGui.QDockWidget.DockWidgetFloatable | QtGui.QDockWidget.DockWidgetClosable)
  476. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  477. if self.defaults["shell_at_startup"]:
  478. self.ui.shell_dock.show()
  479. else:
  480. self.ui.shell_dock.hide()
  481. if self.cmd_line_shellfile:
  482. try:
  483. with open(self.cmd_line_shellfile, "r") as myfile:
  484. cmd_line_shellfile_text = myfile.read()
  485. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  486. except Exception as ext:
  487. print "ERROR: ", ext
  488. sys.exit(2)
  489. # Post-GUI initialization: Experimental attempt
  490. # to perform unit tests on the GUI.
  491. if post_gui is not None:
  492. post_gui(self)
  493. App.log.debug("END of constructor. Releasing control.")
  494. def defaults_read_form(self):
  495. for option in self.defaults_form_fields:
  496. self.defaults[option] = self.defaults_form_fields[option].get_value()
  497. def defaults_write_form(self):
  498. for option in self.defaults:
  499. self.defaults_write_form_field(option)
  500. # try:
  501. # self.defaults_form_fields[option].set_value(self.defaults[option])
  502. # except KeyError:
  503. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  504. # # TODO: Rethink this?
  505. # pass
  506. def defaults_write_form_field(self, field):
  507. try:
  508. self.defaults_form_fields[field].set_value(self.defaults[field])
  509. except KeyError:
  510. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  511. # TODO: Rethink this?
  512. pass
  513. def disable_plots(self, except_current=False):
  514. """
  515. Disables all plots with exception of the current object if specified.
  516. :param except_current: Wether to skip the current object.
  517. :rtype except_current: boolean
  518. :return: None
  519. """
  520. # TODO: This method is very similar to replot_all. Try to merge.
  521. self.progress.emit(10)
  522. def worker_task(app_obj):
  523. percentage = 0.1
  524. try:
  525. delta = 0.9 / len(self.collection.get_list())
  526. except ZeroDivisionError:
  527. self.progress.emit(0)
  528. return
  529. for obj in self.collection.get_list():
  530. if obj != self.collection.get_active() or not except_current:
  531. obj.options['plot'] = False
  532. obj.plot()
  533. percentage += delta
  534. self.progress.emit(int(percentage*100))
  535. self.progress.emit(0)
  536. self.plots_updated.emit()
  537. # Send to worker
  538. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  539. def edit_geometry(self):
  540. """
  541. Send the current geometry object (if any) into the editor.
  542. :return: None
  543. """
  544. if not isinstance(self.collection.get_active(), FlatCAMGeometry):
  545. self.info("Select a Geometry Object to edit.")
  546. return
  547. self.ui.updategeo_btn.setEnabled(True)
  548. self.draw.edit_fcgeometry(self.collection.get_active())
  549. def editor2geometry(self):
  550. """
  551. Transfers the geometry in the editor to the current geometry object.
  552. :return: None
  553. """
  554. geo = self.collection.get_active()
  555. if not isinstance(geo, FlatCAMGeometry):
  556. self.info("Select a Geometry Object to update.")
  557. return
  558. self.draw.update_fcgeometry(geo)
  559. self.draw.deactivate()
  560. self.ui.updategeo_btn.setEnabled(False)
  561. geo.plot()
  562. def get_last_folder(self):
  563. return self.defaults["last_folder"]
  564. def report_usage(self, resource):
  565. """
  566. Increments usage counter for the given resource
  567. in self.defaults['stats'].
  568. :param resource: Name of the resource.
  569. :return: None
  570. """
  571. if resource in self.defaults['stats']:
  572. self.defaults['stats'][resource] += 1
  573. else:
  574. self.defaults['stats'][resource] = 1
  575. def raiseTclError(self, text):
  576. """
  577. this method pass exception from python into TCL as error, so we get stacktrace and reason
  578. :param text: text of error
  579. :return: raise exception
  580. """
  581. self.tcl.eval('return -code error "%s"' % text)
  582. raise Exception(text)
  583. def exec_command(self, text):
  584. """
  585. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  586. :param text: Input command
  587. :return: None
  588. """
  589. self.report_usage('exec_command')
  590. text = str(text)
  591. try:
  592. result = self.tcl.eval(str(text))
  593. self.shell.append_output(result + '\n')
  594. except Tkinter.TclError, e:
  595. #this will display more precise answer if something in TCL shell fail
  596. result = self.tcl.eval("set errorInfo")
  597. self.log.error("Exec command Exception: %s" % (result + '\n'))
  598. self.shell.append_error('ERROR: ' + result + '\n')
  599. #show error in console and just return
  600. return
  601. """
  602. Code below is unsused. Saved for later.
  603. """
  604. parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  605. parts = [p.replace('\n', '').replace('"', '') for p in parts]
  606. self.log.debug(parts)
  607. try:
  608. if parts[0] not in commands:
  609. self.shell.append_error("Unknown command\n")
  610. return
  611. #import inspect
  612. #inspect.getargspec(someMethod)
  613. if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  614. (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  615. self.shell.append_error(
  616. "Command %s takes %d arguments. %d given.\n" %
  617. (parts[0], commands[parts[0]]["params"], len(parts)-1)
  618. )
  619. return
  620. cmdfcn = commands[parts[0]]["fcn"]
  621. cmdconv = commands[parts[0]]["converters"]
  622. if len(parts) - 1 > 0:
  623. retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  624. else:
  625. retval = cmdfcn()
  626. retfcn = commands[parts[0]]["retfcn"]
  627. if retval and retfcn(retval):
  628. self.shell.append_output(retfcn(retval) + "\n")
  629. except Exception, e:
  630. #self.shell.append_error(''.join(traceback.format_exc()))
  631. #self.shell.append_error("?\n")
  632. self.shell.append_error(str(e) + "\n")
  633. def info(self, msg):
  634. """
  635. Writes on the status bar.
  636. :param msg: Text to write.
  637. :return: None
  638. """
  639. match = re.search("\[([^\]]+)\](.*)", msg)
  640. if match:
  641. self.ui.fcinfo.set_status(QtCore.QString(match.group(2)), level=match.group(1))
  642. else:
  643. self.ui.fcinfo.set_status(QtCore.QString(msg), level="info")
  644. def load_defaults(self):
  645. """
  646. Loads the aplication's default settings from defaults.json into
  647. ``self.defaults``.
  648. :return: None
  649. """
  650. try:
  651. f = open(self.data_path + "/defaults.json")
  652. options = f.read()
  653. f.close()
  654. except IOError:
  655. self.log.error("Could not load defaults file.")
  656. self.inform.emit("ERROR: Could not load defaults file.")
  657. return
  658. try:
  659. defaults = json.loads(options)
  660. except:
  661. e = sys.exc_info()[0]
  662. App.log.error(str(e))
  663. self.inform.emit("ERROR: Failed to parse defaults file.")
  664. return
  665. self.defaults.update(defaults)
  666. def save_geometry(self, x, y, width, height):
  667. self.defaults["def_win_x"] = x
  668. self.defaults["def_win_y"] = y
  669. self.defaults["def_win_w"] = width
  670. self.defaults["def_win_h"] = height
  671. self.save_defaults()
  672. def message_dialog(self, title, message, kind="info"):
  673. icon = {"info": QtGui.QMessageBox.Information,
  674. "warning": QtGui.QMessageBox.Warning,
  675. "error": QtGui.QMessageBox.Critical}[str(kind)]
  676. dlg = QtGui.QMessageBox(icon, title, message, parent=self.ui)
  677. dlg.setText(message)
  678. dlg.exec_()
  679. def register_recent(self, kind, filename):
  680. self.log.debug("register_recent()")
  681. self.log.debug(" %s" % kind)
  682. self.log.debug(" %s" % filename)
  683. record = {'kind': str(kind), 'filename': str(filename)}
  684. if record in self.recent:
  685. return
  686. self.recent.insert(0, record)
  687. if len(self.recent) > self.defaults['recent_limit']: # Limit reached
  688. self.recent.pop()
  689. try:
  690. f = open(self.data_path + '/recent.json', 'w')
  691. except IOError:
  692. App.log.error("Failed to open recent items file for writing.")
  693. self.inform.emit('Failed to open recent files file for writing.')
  694. return
  695. #try:
  696. json.dump(self.recent, f)
  697. # except:
  698. # App.log.error("Failed to write to recent items file.")
  699. # self.inform.emit('ERROR: Failed to write to recent items file.')
  700. # f.close()
  701. f.close()
  702. # Re-buid the recent items menu
  703. self.setup_recent_items()
  704. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True):
  705. """
  706. Creates a new specalized FlatCAMObj and attaches it to the application,
  707. this is, updates the GUI accordingly, any other records and plots it.
  708. This method is thread-safe.
  709. :param kind: The kind of object to create. One of 'gerber',
  710. 'excellon', 'cncjob' and 'geometry'.
  711. :type kind: str
  712. :param name: Name for the object.
  713. :type name: str
  714. :param initialize: Function to run after creation of the object
  715. but before it is attached to the application. The function is
  716. called with 2 parameters: the new object and the App instance.
  717. :type initialize: function
  718. :return: None
  719. :rtype: None
  720. """
  721. App.log.debug("new_object()")
  722. t0 = time.time() # Debug
  723. ### Check for existing name
  724. # while name in self.collection.get_names():
  725. # ## Create a new name
  726. # # Ends with number?
  727. # App.log.debug("new_object(): Object name (%s) exists, changing." % name)
  728. # match = re.search(r'(.*[^\d])?(\d+)$', name)
  729. # if match: # Yes: Increment the number!
  730. # base = match.group(1) or ''
  731. # num = int(match.group(2))
  732. # name = base + str(num + 1)
  733. # else: # No: add a number!
  734. # name += "_1"
  735. ## Create object
  736. classdict = {
  737. "gerber": FlatCAMGerber,
  738. "excellon": FlatCAMExcellon,
  739. "cncjob": FlatCAMCNCjob,
  740. "geometry": FlatCAMGeometry
  741. }
  742. App.log.debug("Calling object constructor...")
  743. obj = classdict[kind](name)
  744. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  745. # Set default options from self.options
  746. for option in self.options:
  747. if option.find(kind + "_") == 0:
  748. oname = option[len(kind) + 1:]
  749. obj.options[oname] = self.options[option]
  750. # Initialize as per user request
  751. # User must take care to implement initialize
  752. # in a thread-safe way as is is likely that we
  753. # have been invoked in a separate thread.
  754. t1 = time.time()
  755. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  756. initialize(obj, self)
  757. t2 = time.time()
  758. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  759. # Check units and convert if necessary
  760. # This condition CAN be true because initialize() can change obj.units
  761. if self.options["units"].upper() != obj.units.upper():
  762. self.inform.emit("Converting units to " + self.options["units"] + ".")
  763. obj.convert_units(self.options["units"])
  764. t3 = time.time()
  765. self.log.debug("%f seconds converting units." % (t3 - t2))
  766. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  767. # Move the object to the main thread and let the app know that it is available.
  768. obj.moveToThread(QtGui.QApplication.instance().thread())
  769. self.object_created.emit(obj)
  770. return obj
  771. def options_read_form(self):
  772. for option in self.options_form_fields:
  773. self.options[option] = self.options_form_fields[option].get_value()
  774. def options_write_form(self):
  775. for option in self.options:
  776. self.options_write_form_field(option)
  777. def options_write_form_field(self, field):
  778. try:
  779. self.options_form_fields[field].set_value(self.options[field])
  780. except KeyError:
  781. # Changed from error to debug. This allows to have data stored
  782. # which is not user-editable.
  783. self.log.debug("options_write_form_field(): No field for: %s" % field)
  784. def on_about(self):
  785. """
  786. Displays the "about" dialog.
  787. :return: None
  788. """
  789. self.report_usage("on_about")
  790. version = self.version
  791. version_date = self.version_date
  792. class AboutDialog(QtGui.QDialog):
  793. def __init__(self, parent=None):
  794. QtGui.QDialog.__init__(self, parent)
  795. # Icon and title
  796. self.setWindowIcon(parent.app_icon)
  797. self.setWindowTitle("FlatCAM")
  798. layout1 = QtGui.QVBoxLayout()
  799. self.setLayout(layout1)
  800. layout2 = QtGui.QHBoxLayout()
  801. layout1.addLayout(layout2)
  802. logo = QtGui.QLabel()
  803. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  804. layout2.addWidget(logo, stretch=0)
  805. title = QtGui.QLabel(
  806. "<font size=8><B>FlatCAM</B></font><BR>"
  807. "Version %s (%s)<BR>"
  808. "<BR>"
  809. "2D Computer-Aided Printed Circuit Board<BR>"
  810. "Manufacturing.<BR>"
  811. "<BR>"
  812. "(c) 2014-2015 Juan Pablo Caram" % (version, version_date)
  813. )
  814. layout2.addWidget(title, stretch=1)
  815. layout3 = QtGui.QHBoxLayout()
  816. layout1.addLayout(layout3)
  817. layout3.addStretch()
  818. okbtn = QtGui.QPushButton("Close")
  819. layout3.addWidget(okbtn)
  820. okbtn.clicked.connect(self.accept)
  821. AboutDialog(self.ui).exec_()
  822. def on_file_savedefaults(self):
  823. """
  824. Callback for menu item File->Save Defaults. Saves application default options
  825. ``self.defaults`` to defaults.json.
  826. :return: None
  827. """
  828. self.save_defaults()
  829. def save_defaults(self, silent=False):
  830. """
  831. Saves application default options
  832. ``self.defaults`` to defaults.json.
  833. :return: None
  834. """
  835. self.report_usage("save_defaults")
  836. ## Read options from file ##
  837. try:
  838. f = open(self.data_path + "/defaults.json")
  839. options = f.read()
  840. f.close()
  841. except:
  842. e = sys.exc_info()[0]
  843. App.log.error("Could not load defaults file.")
  844. App.log.error(str(e))
  845. self.inform.emit("[error] Could not load defaults file.")
  846. return
  847. try:
  848. defaults = json.loads(options)
  849. except:
  850. e = sys.exc_info()[0]
  851. App.log.error("Failed to parse defaults file.")
  852. App.log.error(str(e))
  853. self.inform.emit("[error] Failed to parse defaults file.")
  854. return
  855. # Update options
  856. self.defaults_read_form()
  857. defaults.update(self.defaults)
  858. # Save update options
  859. try:
  860. f = open(self.data_path + "/defaults.json", "w")
  861. json.dump(defaults, f)
  862. f.close()
  863. except:
  864. self.inform.emit("[error] Failed to write defaults to file.")
  865. return
  866. if not silent:
  867. self.inform.emit("Defaults saved.")
  868. def on_toggle_shell(self):
  869. """
  870. toggle shell if is visible close it if closed open it
  871. :return:
  872. """
  873. if self.ui.shell_dock.isVisible():
  874. self.ui.shell_dock.hide()
  875. else:
  876. self.ui.shell_dock.show()
  877. def on_edit_join(self):
  878. """
  879. Callback for Edit->Join. Joins the selected geometry objects into
  880. a new one.
  881. :return: None
  882. """
  883. objs = self.collection.get_selected()
  884. def initialize(obj, app):
  885. FlatCAMGeometry.merge(objs, obj)
  886. self.new_object("geometry", "Combo", initialize)
  887. def on_options_app2project(self):
  888. """
  889. Callback for Options->Transfer Options->App=>Project. Copies options
  890. from application defaults to project defaults.
  891. :return: None
  892. """
  893. self.report_usage("on_options_app2project")
  894. self.defaults_read_form()
  895. self.options.update(self.defaults)
  896. self.options_write_form()
  897. def on_options_project2app(self):
  898. """
  899. Callback for Options->Transfer Options->Project=>App. Copies options
  900. from project defaults to application defaults.
  901. :return: None
  902. """
  903. self.report_usage("on_options_project2app")
  904. self.options_read_form()
  905. self.defaults.update(self.options)
  906. self.defaults_write_form()
  907. def on_options_project2object(self):
  908. """
  909. Callback for Options->Transfer Options->Project=>Object. Copies options
  910. from project defaults to the currently selected object.
  911. :return: None
  912. """
  913. self.report_usage("on_options_project2object")
  914. self.options_read_form()
  915. obj = self.collection.get_active()
  916. if obj is None:
  917. self.inform.emit("WARNING: No object selected.")
  918. return
  919. for option in self.options:
  920. if option.find(obj.kind + "_") == 0:
  921. oname = option[len(obj.kind)+1:]
  922. obj.options[oname] = self.options[option]
  923. obj.to_form() # Update UI
  924. def on_options_object2project(self):
  925. """
  926. Callback for Options->Transfer Options->Object=>Project. Copies options
  927. from the currently selected object to project defaults.
  928. :return: None
  929. """
  930. self.report_usage("on_options_object2project")
  931. obj = self.collection.get_active()
  932. if obj is None:
  933. self.inform.emit("WARNING: No object selected.")
  934. return
  935. obj.read_form()
  936. for option in obj.options:
  937. if option in ['name']: # TODO: Handle this better...
  938. continue
  939. self.options[obj.kind + "_" + option] = obj.options[option]
  940. self.options_write_form()
  941. def on_options_object2app(self):
  942. """
  943. Callback for Options->Transfer Options->Object=>App. Copies options
  944. from the currently selected object to application defaults.
  945. :return: None
  946. """
  947. self.report_usage("on_options_object2app")
  948. obj = self.collection.get_active()
  949. if obj is None:
  950. self.inform.emit("WARNING: No object selected.")
  951. return
  952. obj.read_form()
  953. for option in obj.options:
  954. if option in ['name']: # TODO: Handle this better...
  955. continue
  956. self.defaults[obj.kind + "_" + option] = obj.options[option]
  957. self.defaults_write_form()
  958. def on_options_app2object(self):
  959. """
  960. Callback for Options->Transfer Options->App=>Object. Copies options
  961. from application defaults to the currently selected object.
  962. :return: None
  963. """
  964. self.report_usage("on_options_app2object")
  965. self.defaults_read_form()
  966. obj = self.collection.get_active()
  967. if obj is None:
  968. self.inform.emit("WARNING: No object selected.")
  969. return
  970. for option in self.defaults:
  971. if option.find(obj.kind + "_") == 0:
  972. oname = option[len(obj.kind)+1:]
  973. obj.options[oname] = self.defaults[option]
  974. obj.to_form() # Update UI
  975. def on_options_dict_change(self, field):
  976. self.options_write_form_field(field)
  977. if field == "units":
  978. self.set_screen_units(self.options['units'])
  979. def on_defaults_dict_change(self, field):
  980. self.defaults_write_form_field(field)
  981. def set_screen_units(self, units):
  982. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  983. def on_toggle_units(self):
  984. """
  985. Callback for the Units radio-button change in the Options tab.
  986. Changes the application's default units or the current project's units.
  987. If changing the project's units, the change propagates to all of
  988. the objects in the project.
  989. :return: None
  990. """
  991. self.report_usage("on_toggle_units")
  992. if self.toggle_units_ignore:
  993. return
  994. # If option is the same, then ignore
  995. if self.options_form.units_radio.get_value().upper() == self.options['units'].upper():
  996. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  997. return
  998. # Options to scale
  999. dimensions = ['gerber_isotooldia', 'gerber_cutoutmargin', 'gerber_cutoutgapsize',
  1000. 'gerber_noncoppermargin', 'gerber_bboxmargin', 'excellon_drillz',
  1001. 'excellon_travelz', 'excellon_feedrate', 'excellon_toolchangez', 'cncjob_tooldia',
  1002. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate',
  1003. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap',
  1004. 'geometry_paintmargin']
  1005. def scale_options(sfactor):
  1006. for dim in dimensions:
  1007. self.options[dim] *= sfactor
  1008. # The scaling factor depending on choice of units.
  1009. factor = 1/25.4
  1010. if self.options_form.units_radio.get_value().upper() == 'MM':
  1011. factor = 25.4
  1012. # Changing project units. Warn user.
  1013. msgbox = QtGui.QMessageBox()
  1014. msgbox.setText("<B>Change project units ...</B>")
  1015. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  1016. "properties of all objects to be scaled accordingly. Continue?")
  1017. msgbox.setStandardButtons(QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Ok)
  1018. msgbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1019. response = msgbox.exec_()
  1020. if response == QtGui.QMessageBox.Ok:
  1021. self.options_read_form()
  1022. scale_options(factor)
  1023. self.options_write_form()
  1024. for obj in self.collection.get_list():
  1025. units = self.options_form.units_radio.get_value().upper()
  1026. obj.convert_units(units)
  1027. current = self.collection.get_active()
  1028. if current is not None:
  1029. current.to_form()
  1030. self.plot_all()
  1031. else:
  1032. # Undo toggling
  1033. self.toggle_units_ignore = True
  1034. if self.options_form.units_radio.get_value().upper() == 'MM':
  1035. self.options_form.units_radio.set_value('IN')
  1036. else:
  1037. self.options_form.units_radio.set_value('MM')
  1038. self.toggle_units_ignore = False
  1039. self.options_read_form()
  1040. self.inform.emit("Converted units to %s" % self.options["units"])
  1041. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  1042. self.set_screen_units(self.options["units"])
  1043. def on_options_combo_change(self, sel):
  1044. """
  1045. Called when the combo box to choose between application defaults and
  1046. project option changes value. The corresponding variables are
  1047. copied to the UI.
  1048. :param sel: The option index that was chosen.
  1049. :return: None
  1050. """
  1051. # combo_sel = self.ui.notebook.combo_options.get_active()
  1052. App.log.debug("Options --> %s" % sel)
  1053. # Remove anything else in the box
  1054. # box_children = self.options_box.get_children()
  1055. # box_children = self.ui.notebook.options_contents.get_children()
  1056. # for child in box_children:
  1057. # self.ui.notebook.options_contents.remove(child)
  1058. # try:
  1059. # self.ui.options_area.removeWidget(self.defaults_form)
  1060. # except:
  1061. # pass
  1062. #
  1063. # try:
  1064. # self.ui.options_area.removeWidget(self.options_form)
  1065. # except:
  1066. # pass
  1067. form = [self.defaults_form, self.options_form][sel]
  1068. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  1069. try:
  1070. self.ui.options_scroll_area.takeWidget()
  1071. except:
  1072. self.log.debug("Nothing to remove")
  1073. self.ui.options_scroll_area.setWidget(form)
  1074. form.show()
  1075. # self.options2form()
  1076. def on_delete(self):
  1077. """
  1078. Delete the currently selected FlatCAMObjs.
  1079. :return: None
  1080. """
  1081. self.log.debug("on_delete()")
  1082. self.report_usage("on_delete")
  1083. while (self.collection.get_active()):
  1084. self.delete_first_selected()
  1085. def delete_first_selected(self):
  1086. # Keep this for later
  1087. try:
  1088. name = self.collection.get_active().options["name"]
  1089. except AttributeError:
  1090. self.log.debug("Nothing selected for deletion")
  1091. return
  1092. # Remove plot
  1093. self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  1094. self.plotcanvas.auto_adjust_axes()
  1095. # Clear form
  1096. self.setup_component_editor()
  1097. # Remove from dictionary
  1098. self.collection.delete_active()
  1099. self.inform.emit("Object deleted: %s" % name)
  1100. def on_plots_updated(self):
  1101. """
  1102. Callback used to report when the plots have changed.
  1103. Adjust axes and zooms to fit.
  1104. :return: None
  1105. """
  1106. self.plotcanvas.auto_adjust_axes()
  1107. self.on_zoom_fit(None)
  1108. def on_toolbar_replot(self):
  1109. """
  1110. Callback for toolbar button. Re-plots all objects.
  1111. :return: None
  1112. """
  1113. self.report_usage("on_toolbar_replot")
  1114. self.log.debug("on_toolbar_replot()")
  1115. try:
  1116. self.collection.get_active().read_form()
  1117. except AttributeError:
  1118. self.log.debug("on_toolbar_replot(): AttributeError")
  1119. pass
  1120. self.plot_all()
  1121. def on_row_activated(self, index):
  1122. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1123. def on_object_created(self, obj):
  1124. """
  1125. Event callback for object creation.
  1126. :param obj: The newly created FlatCAM object.
  1127. :return: None
  1128. """
  1129. t0 = time.time() # DEBUG
  1130. self.log.debug("on_object_created()")
  1131. # The Collection might change the name if there is a collision
  1132. self.collection.append(obj)
  1133. self.inform.emit("Object (%s) created: %s" % (obj.kind, obj.options['name']))
  1134. self.new_object_available.emit(obj)
  1135. obj.plot()
  1136. self.on_zoom_fit(None)
  1137. t1 = time.time() # DEBUG
  1138. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1139. def on_zoom_fit(self, event):
  1140. """
  1141. Callback for zoom-out request. This can be either from the corresponding
  1142. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  1143. with axes limits from the geometry bounds of all objects.
  1144. :param event: Ignored.
  1145. :return: None
  1146. """
  1147. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  1148. width = xmax - xmin
  1149. height = ymax - ymin
  1150. xmin -= 0.05 * width
  1151. xmax += 0.05 * width
  1152. ymin -= 0.05 * height
  1153. ymax += 0.05 * height
  1154. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  1155. def on_key_over_plot(self, event):
  1156. """
  1157. Callback for the key pressed event when the canvas is focused. Keyboard
  1158. shortcuts are handled here. So far, these are the shortcuts:
  1159. ========== ============================================
  1160. Key Action
  1161. ========== ============================================
  1162. '1' Zoom-fit. Fits the axes limits to the data.
  1163. '2' Zoom-out.
  1164. '3' Zoom-in.
  1165. 'm' Toggle on-off the measuring tool.
  1166. ========== ============================================
  1167. :param event: Ignored.
  1168. :return: None
  1169. """
  1170. if event.key == self.defaults['fit_key']: # 1
  1171. self.on_zoom_fit(None)
  1172. return
  1173. if event.key == self.defaults['zoom_out_key']: # 2
  1174. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  1175. return
  1176. if event.key == self.defaults['zoom_in_key']: # 3
  1177. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  1178. return
  1179. # if event.key == 'm':
  1180. # if self.measure.toggle_active():
  1181. # self.inform.emit("Measuring tool ON")
  1182. # else:
  1183. # self.inform.emit("Measuring tool OFF")
  1184. # return
  1185. def on_click_over_plot(self, event):
  1186. """
  1187. Callback for the mouse click event over the plot. This event is generated
  1188. by the Matplotlib backend and has been registered in ``self.__init__()``.
  1189. For details, see: http://matplotlib.org/users/event_handling.html
  1190. Default actions are:
  1191. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  1192. :param event: Contains information about the event, like which button
  1193. was clicked, the pixel coordinates and the axes coordinates.
  1194. :return: None
  1195. """
  1196. # So it can receive key presses
  1197. self.plotcanvas.canvas.setFocus()
  1198. try:
  1199. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  1200. event.button, event.x, event.y, event.xdata, event.ydata))
  1201. self.clipboard.setText(self.defaults["point_clipboard_format"] % (event.xdata, event.ydata))
  1202. except Exception, e:
  1203. App.log.debug("Outside plot?")
  1204. App.log.debug(str(e))
  1205. def on_mouse_move_over_plot(self, event):
  1206. """
  1207. Callback for the mouse motion event over the plot. This event is generated
  1208. by the Matplotlib backend and has been registered in ``self.__init__()``.
  1209. For details, see: http://matplotlib.org/users/event_handling.html
  1210. :param event: Contains information about the event.
  1211. :return: None
  1212. """
  1213. try: # May fail in case mouse not within axes
  1214. self.ui.position_label.setText("X: %.4f Y: %.4f" % (
  1215. event.xdata, event.ydata))
  1216. self.mouse = [event.xdata, event.ydata]
  1217. except:
  1218. self.ui.position_label.setText("")
  1219. self.mouse = None
  1220. def on_file_new(self):
  1221. """
  1222. Callback for menu item File->New. Returns the application to its
  1223. startup state. This method is thread-safe.
  1224. :return: None
  1225. """
  1226. self.report_usage("on_file_new")
  1227. # Remove everything from memory
  1228. App.log.debug("on_file_new()")
  1229. self.plotcanvas.clear()
  1230. self.collection.delete_all()
  1231. self.setup_component_editor()
  1232. # Clear project filename
  1233. self.project_filename = None
  1234. # Re-fresh project options
  1235. self.on_options_app2project()
  1236. def on_fileopengerber(self):
  1237. """
  1238. File menu callback for opening a Gerber.
  1239. :return: None
  1240. """
  1241. self.report_usage("on_fileopengerber")
  1242. App.log.debug("on_fileopengerber()")
  1243. try:
  1244. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Gerber",
  1245. directory=self.get_last_folder())
  1246. except TypeError:
  1247. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Gerber")
  1248. # The Qt methods above will return a QString which can cause problems later.
  1249. # So far json.dump() will fail to serialize it.
  1250. # TODO: Improve the serialization methods and remove this fix.
  1251. filename = str(filename)
  1252. if str(filename) == "":
  1253. self.inform.emit("Open cancelled.")
  1254. else:
  1255. self.worker_task.emit({'fcn': self.open_gerber,
  1256. 'params': [filename]})
  1257. def on_fileopenexcellon(self):
  1258. """
  1259. File menu callback for opening an Excellon file.
  1260. :return: None
  1261. """
  1262. self.report_usage("on_fileopenexcellon")
  1263. App.log.debug("on_fileopenexcellon()")
  1264. try:
  1265. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Excellon",
  1266. directory=self.get_last_folder())
  1267. except TypeError:
  1268. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Excellon")
  1269. # The Qt methods above will return a QString which can cause problems later.
  1270. # So far json.dump() will fail to serialize it.
  1271. # TODO: Improve the serialization methods and remove this fix.
  1272. filename = str(filename)
  1273. if str(filename) == "":
  1274. self.inform.emit("Open cancelled.")
  1275. else:
  1276. self.worker_task.emit({'fcn': self.open_excellon,
  1277. 'params': [filename]})
  1278. def on_fileopengcode(self):
  1279. """
  1280. File menu call back for opening gcode.
  1281. :return: None
  1282. """
  1283. self.report_usage("on_fileopengcode")
  1284. App.log.debug("on_fileopengcode()")
  1285. try:
  1286. filename = QtGui.QFileDialog.getOpenFileName(caption="Open G-Code",
  1287. directory=self.get_last_folder())
  1288. except TypeError:
  1289. filename = QtGui.QFileDialog.getOpenFileName(caption="Open G-Code")
  1290. # The Qt methods above will return a QString which can cause problems later.
  1291. # So far json.dump() will fail to serialize it.
  1292. # TODO: Improve the serialization methods and remove this fix.
  1293. filename = str(filename)
  1294. if str(filename) == "":
  1295. self.inform.emit("Open cancelled.")
  1296. else:
  1297. self.worker_task.emit({'fcn': self.open_gcode,
  1298. 'params': [filename]})
  1299. def on_file_openproject(self):
  1300. """
  1301. File menu callback for opening a project.
  1302. :return: None
  1303. """
  1304. self.report_usage("on_file_openproject")
  1305. App.log.debug("on_file_openproject()")
  1306. try:
  1307. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Project",
  1308. directory=self.get_last_folder())
  1309. except TypeError:
  1310. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Project")
  1311. # The Qt methods above will return a QString which can cause problems later.
  1312. # So far json.dump() will fail to serialize it.
  1313. # TODO: Improve the serialization methods and remove this fix.
  1314. filename = str(filename)
  1315. if str(filename) == "":
  1316. self.inform.emit("Open cancelled.")
  1317. else:
  1318. # self.worker_task.emit({'fcn': self.open_project,
  1319. # 'params': [filename]})
  1320. # The above was failing because open_project() is not
  1321. # thread safe. The new_project()
  1322. self.open_project(filename)
  1323. def on_file_exportsvg(self):
  1324. """
  1325. Callback for menu item File->Export SVG.
  1326. :return: None
  1327. """
  1328. self.report_usage("on_file_exportsvg")
  1329. App.log.debug("on_file_exportsvg()")
  1330. obj = self.collection.get_active()
  1331. if obj is None:
  1332. self.inform.emit("WARNING: No object selected.")
  1333. msg = "Please Select a Geometry object to export"
  1334. msgbox = QtGui.QMessageBox()
  1335. msgbox.setInformativeText(msg)
  1336. msgbox.setStandardButtons(QtGui.QMessageBox.Ok)
  1337. msgbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1338. msgbox.exec_()
  1339. return
  1340. # Check for more compatible types and add as required
  1341. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  1342. and not isinstance(obj, FlatCAMExcellon)):
  1343. msg = "ERROR: Only Geometry, Gerber and CNCJob objects can be used."
  1344. msgbox = QtGui.QMessageBox()
  1345. msgbox.setInformativeText(msg)
  1346. msgbox.setStandardButtons(QtGui.QMessageBox.Ok)
  1347. msgbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1348. msgbox.exec_()
  1349. return
  1350. name = self.collection.get_active().options["name"]
  1351. try:
  1352. filename = QtGui.QFileDialog.getSaveFileName(caption="Export SVG",
  1353. directory=self.get_last_folder(), filter="*.svg")
  1354. except TypeError:
  1355. filename = QtGui.QFileDialog.getSaveFileName(caption="Export SVG")
  1356. filename = str(filename)
  1357. if str(filename) == "":
  1358. self.inform.emit("Export SVG cancelled.")
  1359. return
  1360. else:
  1361. self.export_svg(name, filename)
  1362. def on_file_importsvg(self):
  1363. """
  1364. Callback for menu item File->Import SVG.
  1365. :return: None
  1366. """
  1367. self.report_usage("on_file_importsvg")
  1368. App.log.debug("on_file_importsvg()")
  1369. try:
  1370. filename = QtGui.QFileDialog.getOpenFileName(caption="Import SVG",
  1371. directory=self.get_last_folder())
  1372. except TypeError:
  1373. filename = QtGui.QFileDialog.getOpenFileName(caption="Import SVG")
  1374. filename = str(filename)
  1375. if str(filename) == "":
  1376. self.inform.emit("Open cancelled.")
  1377. else:
  1378. self.worker_task.emit({'fcn': self.import_svg,
  1379. 'params': [filename]})
  1380. def on_file_saveproject(self):
  1381. """
  1382. Callback for menu item File->Save Project. Saves the project to
  1383. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  1384. if set to None. The project is saved by calling ``self.save_project()``.
  1385. :return: None
  1386. """
  1387. self.report_usage("on_file_saveproject")
  1388. if self.project_filename is None:
  1389. self.on_file_saveprojectas()
  1390. else:
  1391. self.save_project(self.project_filename)
  1392. self.file_opened.emit("project", self.project_filename)
  1393. self.inform.emit("Project saved to: " + self.project_filename)
  1394. def on_file_saveprojectas(self, make_copy=False):
  1395. """
  1396. Callback for menu item File->Save Project As... Opens a file
  1397. chooser and saves the project to the given file via
  1398. ``self.save_project()``.
  1399. :return: None
  1400. """
  1401. self.report_usage("on_file_saveprojectas")
  1402. try:
  1403. filename = QtGui.QFileDialog.getSaveFileName(caption="Save Project As ...",
  1404. directory=self.get_last_folder())
  1405. except TypeError:
  1406. filename = QtGui.QFileDialog.getSaveFileName(caption="Save Project As ...")
  1407. try:
  1408. f = open(filename, 'r')
  1409. f.close()
  1410. exists = True
  1411. except IOError:
  1412. exists = False
  1413. msg = "File exists. Overwrite?"
  1414. if exists:
  1415. msgbox = QtGui.QMessageBox()
  1416. msgbox.setInformativeText(msg)
  1417. msgbox.setStandardButtons(QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Ok)
  1418. msgbox.setDefaultButton(QtGui.QMessageBox.Cancel)
  1419. result = msgbox.exec_()
  1420. if result == QtGui.QMessageBox.Cancel:
  1421. return
  1422. self.save_project(filename)
  1423. self.file_opened.emit("project", filename)
  1424. if not make_copy:
  1425. self.project_filename = filename
  1426. self.inform.emit("Project saved to: " + self.project_filename)
  1427. else:
  1428. self.inform.emit("Project copy saved to: " + self.project_filename)
  1429. def export_svg(self, obj_name, filename, scale_factor=0.00):
  1430. """
  1431. Exports a Geometry Object to a SVG File
  1432. :param filename: Path to the SVG file to save to.
  1433. :param outname:
  1434. :return:
  1435. """
  1436. self.log.debug("export_svg()")
  1437. try:
  1438. obj = self.collection.get_by_name(str(obj_name))
  1439. except:
  1440. return "Could not retrieve object: %s" % obj_name
  1441. with self.proc_container.new("Exporting SVG") as proc:
  1442. exported_svg = obj.export_svg(scale_factor=scale_factor)
  1443. # Determine bounding area for svg export
  1444. bounds = obj.bounds()
  1445. size = obj.size()
  1446. # Convert everything to strings for use in the xml doc
  1447. svgwidth = str(size[0])
  1448. svgheight = str(size[1])
  1449. minx = str(bounds[0])
  1450. miny = str(bounds[1] - size[1])
  1451. uom = obj.units.lower()
  1452. # Add a SVG Header and footer to the svg output from shapely
  1453. # The transform flips the Y Axis so that everything renders properly within svg apps such as inkscape
  1454. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  1455. svg_header += 'width="' + svgwidth + uom + '" '
  1456. svg_header += 'height="' + svgheight + uom + '" '
  1457. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  1458. svg_header += '<g transform="scale(1,-1)">'
  1459. svg_footer = '</g> </svg>'
  1460. svg_elem = svg_header + exported_svg + svg_footer
  1461. # Parse the xml through a xml parser just to add line feeds and to make it look more pretty for the output
  1462. doc = parse_xml_string(svg_elem)
  1463. with open(filename, 'w') as fp:
  1464. fp.write(doc.toprettyxml())
  1465. def import_svg(self, filename, outname=None):
  1466. """
  1467. Adds a new Geometry Object to the projects and populates
  1468. it with shapes extracted from the SVG file.
  1469. :param filename: Path to the SVG file.
  1470. :param outname:
  1471. :return:
  1472. """
  1473. def obj_init(geo_obj, app_obj):
  1474. geo_obj.import_svg(filename)
  1475. with self.proc_container.new("Importing SVG") as proc:
  1476. # Object name
  1477. name = outname or filename.split('/')[-1].split('\\')[-1]
  1478. self.new_object("geometry", name, obj_init)
  1479. # Register recent file
  1480. self.file_opened.emit("svg", filename)
  1481. # GUI feedback
  1482. self.inform.emit("Opened: " + filename)
  1483. def open_gerber(self, filename, follow=False, outname=None):
  1484. """
  1485. Opens a Gerber file, parses it and creates a new object for
  1486. it in the program. Thread-safe.
  1487. :param filename: Gerber file filename
  1488. :type filename: str
  1489. :param follow: If true, the parser will not create polygons, just lines
  1490. following the gerber path.
  1491. :type follow: bool
  1492. :return: None
  1493. """
  1494. # How the object should be initialized
  1495. def obj_init(gerber_obj, app_obj):
  1496. assert isinstance(gerber_obj, FlatCAMGerber), \
  1497. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  1498. # Opening the file happens here
  1499. self.progress.emit(30)
  1500. try:
  1501. gerber_obj.parse_file(filename, follow=follow)
  1502. except IOError:
  1503. app_obj.inform.emit("[error] Failed to open file: " + filename)
  1504. app_obj.progress.emit(0)
  1505. raise IOError('Failed to open file: ' + filename)
  1506. except ParseError, e:
  1507. app_obj.inform.emit("[error] Failed to parse file: " + filename + ". " + e[0])
  1508. app_obj.progress.emit(0)
  1509. self.log.error(str(e))
  1510. raise
  1511. # Further parsing
  1512. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  1513. App.log.debug("open_gerber()")
  1514. with self.proc_container.new("Opening Gerber") as proc:
  1515. self.progress.emit(10)
  1516. # Object name
  1517. name = outname or filename.split('/')[-1].split('\\')[-1]
  1518. ### Object creation ###
  1519. self.new_object("gerber", name, obj_init)
  1520. # Register recent file
  1521. self.file_opened.emit("gerber", filename)
  1522. self.progress.emit(100)
  1523. #proc.done()
  1524. # GUI feedback
  1525. self.inform.emit("Opened: " + filename)
  1526. def open_excellon(self, filename, outname=None):
  1527. """
  1528. Opens an Excellon file, parses it and creates a new object for
  1529. it in the program. Thread-safe.
  1530. :param filename: Excellon file filename
  1531. :type filename: str
  1532. :return: None
  1533. """
  1534. App.log.debug("open_excellon()")
  1535. #self.progress.emit(10)
  1536. # How the object should be initialized
  1537. def obj_init(excellon_obj, app_obj):
  1538. #self.progress.emit(20)
  1539. try:
  1540. excellon_obj.parse_file(filename)
  1541. except IOError:
  1542. app_obj.inform.emit("[error] Cannot open file: " + filename)
  1543. self.progress.emit(0) # TODO: self and app_bjj mixed
  1544. raise IOError("Cannot open file: " + filename)
  1545. try:
  1546. excellon_obj.create_geometry()
  1547. except Exception as e:
  1548. app_obj.inform.emit("[error] Failed to create geometry after parsing: " + filename)
  1549. self.progress.emit(0)
  1550. raise e
  1551. #self.progress.emit(70)
  1552. with self.proc_container.new("Opening Excellon."):
  1553. # Object name
  1554. name = outname or filename.split('/')[-1].split('\\')[-1]
  1555. self.new_object("excellon", name, obj_init)
  1556. # Register recent file
  1557. self.file_opened.emit("excellon", filename)
  1558. # GUI feedback
  1559. self.inform.emit("Opened: " + filename)
  1560. #self.progress.emit(100)
  1561. def open_gcode(self, filename, outname=None):
  1562. """
  1563. Opens a G-gcode file, parses it and creates a new object for
  1564. it in the program. Thread-safe.
  1565. :param filename: G-code file filename
  1566. :type filename: str
  1567. :return: None
  1568. """
  1569. App.log.debug("open_gcode()")
  1570. # How the object should be initialized
  1571. def obj_init(job_obj, app_obj_):
  1572. """
  1573. :type app_obj_: App
  1574. """
  1575. assert isinstance(app_obj_, App), \
  1576. "Initializer expected App, got %s" % type(app_obj_)
  1577. self.progress.emit(10)
  1578. try:
  1579. f = open(filename)
  1580. gcode = f.read()
  1581. f.close()
  1582. except IOError:
  1583. app_obj_.inform.emit("[error] Failed to open " + filename)
  1584. self.progress.emit(0)
  1585. raise IOError("Failed to open " + filename)
  1586. job_obj.gcode = gcode
  1587. self.progress.emit(20)
  1588. job_obj.gcode_parse()
  1589. self.progress.emit(60)
  1590. job_obj.create_geometry()
  1591. with self.proc_container.new("Opening G-Code."):
  1592. # Object name
  1593. name = outname or filename.split('/')[-1].split('\\')[-1]
  1594. # New object creation and file processing
  1595. try:
  1596. self.new_object("cncjob", name, obj_init)
  1597. except Exception as e:
  1598. # e = sys.exc_info()
  1599. App.log.error(str(e))
  1600. self.message_dialog("Failed to create CNCJob Object",
  1601. "Attempting to create a FlatCAM CNCJob Object from " +
  1602. "G-Code file failed during processing:\n" +
  1603. str(e[0]) + " " + str(e[1]), kind="error")
  1604. self.progress.emit(0)
  1605. self.collection.delete_active()
  1606. raise e
  1607. # Register recent file
  1608. self.file_opened.emit("cncjob", filename)
  1609. # GUI feedback
  1610. self.inform.emit("Opened: " + filename)
  1611. self.progress.emit(100)
  1612. def open_project(self, filename):
  1613. """
  1614. Loads a project from the specified file.
  1615. 1) Loads and parses file
  1616. 2) Registers the file as recently opened.
  1617. 3) Calls on_file_new()
  1618. 4) Updates options
  1619. 5) Calls new_object() with the object's from_dict() as init method.
  1620. 6) Calls plot_all()
  1621. :param filename: Name of the file from which to load.
  1622. :type filename: str
  1623. :return: None
  1624. """
  1625. App.log.debug("Opening project: " + filename)
  1626. ## Open and parse
  1627. try:
  1628. f = open(filename, 'r')
  1629. except IOError:
  1630. App.log.error("Failed to open project file: %s" % filename)
  1631. self.inform.emit("[error] Failed to open project file: %s" % filename)
  1632. return
  1633. try:
  1634. d = json.load(f, object_hook=dict2obj)
  1635. except:
  1636. App.log.error("Failed to parse project file: %s" % filename)
  1637. self.inform.emit("[error] Failed to parse project file: %s" % filename)
  1638. f.close()
  1639. return
  1640. self.file_opened.emit("project", filename)
  1641. ## Clear the current project
  1642. ## NOT THREAD SAFE ##
  1643. self.on_file_new()
  1644. ##Project options
  1645. self.options.update(d['options'])
  1646. self.project_filename = filename
  1647. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  1648. self.set_screen_units(self.options["units"])
  1649. ## Re create objects
  1650. App.log.debug("Re-creating objects...")
  1651. for obj in d['objs']:
  1652. def obj_init(obj_inst, app_inst):
  1653. obj_inst.from_dict(obj)
  1654. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  1655. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=False)
  1656. self.plot_all()
  1657. self.inform.emit("Project loaded from: " + filename)
  1658. App.log.debug("Project loaded")
  1659. def propagate_defaults(self):
  1660. """
  1661. This method is used to set default values in classes. It's
  1662. an alternative to project options but allows the use
  1663. of values invisible to the user.
  1664. :return: None
  1665. """
  1666. self.log.debug("propagate_defaults()")
  1667. # Which objects to update the given parameters.
  1668. routes = {
  1669. "zdownrate": CNCjob,
  1670. "excellon_zeros": Excellon,
  1671. "gerber_use_buffer_for_union": Gerber,
  1672. "cncjob_coordinate_format": CNCjob
  1673. # "spindlespeed": CNCjob
  1674. }
  1675. for param in routes:
  1676. if param in routes[param].defaults:
  1677. try:
  1678. routes[param].defaults[param] = self.defaults[param]
  1679. self.log.debug(" " + param + " OK")
  1680. except KeyError:
  1681. self.log.debug(" ERROR: " + param + " not in defaults.")
  1682. else:
  1683. # Try extracting the name:
  1684. # classname_param here is param in the object
  1685. if param.find(routes[param].__name__.lower() + "_") == 0:
  1686. p = param[len(routes[param].__name__) + 1:]
  1687. if p in routes[param].defaults:
  1688. routes[param].defaults[p] = self.defaults[param]
  1689. self.log.debug(" " + param + " OK!")
  1690. def restore_main_win_geom(self):
  1691. self.ui.setGeometry(self.defaults["def_win_x"],
  1692. self.defaults["def_win_y"],
  1693. self.defaults["def_win_w"],
  1694. self.defaults["def_win_h"])
  1695. def plot_all(self):
  1696. """
  1697. Re-generates all plots from all objects.
  1698. :return: None
  1699. """
  1700. self.log.debug("plot_all()")
  1701. self.plotcanvas.clear()
  1702. self.progress.emit(10)
  1703. def worker_task(app_obj):
  1704. percentage = 0.1
  1705. try:
  1706. delta = 0.9 / len(self.collection.get_list())
  1707. except ZeroDivisionError:
  1708. self.progress.emit(0)
  1709. return
  1710. for obj in self.collection.get_list():
  1711. obj.plot()
  1712. percentage += delta
  1713. self.progress.emit(int(percentage*100))
  1714. self.progress.emit(0)
  1715. self.plots_updated.emit()
  1716. # Send to worker
  1717. #self.worker.add_task(worker_task, [self])
  1718. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  1719. def register_folder(self, filename):
  1720. self.defaults["last_folder"] = os.path.split(str(filename))[0]
  1721. def set_progress_bar(self, percentage, text=""):
  1722. self.ui.progress_bar.setValue(int(percentage))
  1723. def setup_shell(self):
  1724. """
  1725. Creates shell functions. Runs once at startup.
  1726. :return: None
  1727. """
  1728. self.log.debug("setup_shell()")
  1729. def shelp(p=None):
  1730. if not p:
  1731. return "Available commands:\n" + \
  1732. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  1733. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  1734. if p not in commands:
  1735. return "Unknown command: %s" % p
  1736. return commands[p]["help"]
  1737. def options(name):
  1738. ops = self.collection.get_by_name(str(name)).options
  1739. return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  1740. def h(*args):
  1741. """
  1742. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  1743. and standalone parameters into list.
  1744. """
  1745. kwa = {}
  1746. a = []
  1747. n = len(args)
  1748. name = None
  1749. for i in range(n):
  1750. match = re.search(r'^-([a-zA-Z].*)', args[i])
  1751. if match:
  1752. assert name is None
  1753. name = match.group(1)
  1754. continue
  1755. if name is None:
  1756. a.append(args[i])
  1757. else:
  1758. kwa[name] = args[i]
  1759. name = None
  1760. return a, kwa
  1761. @contextmanager
  1762. def wait_signal(signal, timeout=10000):
  1763. """
  1764. Block loop until signal emitted, timeout (ms) elapses
  1765. or unhandled exception happens in a thread.
  1766. :param signal: Signal to wait for.
  1767. """
  1768. loop = QtCore.QEventLoop()
  1769. # Normal termination
  1770. signal.connect(loop.quit)
  1771. # Termination by exception in thread
  1772. self.thread_exception.connect(loop.quit)
  1773. status = {'timed_out': False}
  1774. def report_quit():
  1775. status['timed_out'] = True
  1776. loop.quit()
  1777. yield
  1778. # Temporarily change how exceptions are managed.
  1779. oeh = sys.excepthook
  1780. ex = []
  1781. def except_hook(type_, value, traceback_):
  1782. ex.append(value)
  1783. oeh(type_, value, traceback_)
  1784. sys.excepthook = except_hook
  1785. # Terminate on timeout
  1786. if timeout is not None:
  1787. QtCore.QTimer.singleShot(timeout, report_quit)
  1788. #### Block ####
  1789. loop.exec_()
  1790. # Restore exception management
  1791. sys.excepthook = oeh
  1792. if ex:
  1793. self.raiseTclError(str(ex[0]))
  1794. if status['timed_out']:
  1795. raise Exception('Timed out!')
  1796. # def wait_signal2(signal, timeout=10000):
  1797. # """Block loop until signal emitted, or timeout (ms) elapses."""
  1798. # loop = QtCore.QEventLoop()
  1799. # signal.connect(loop.quit)
  1800. # status = {'timed_out': False}
  1801. #
  1802. # def report_quit():
  1803. # status['timed_out'] = True
  1804. # loop.quit()
  1805. #
  1806. # if timeout is not None:
  1807. # QtCore.QTimer.singleShot(timeout, report_quit)
  1808. # loop.exec_()
  1809. #
  1810. # if status['timed_out']:
  1811. # raise Exception('Timed out!')
  1812. def mytest(*args):
  1813. to = int(args[0])
  1814. try:
  1815. for rec in self.recent:
  1816. if rec['kind'] == 'gerber':
  1817. self.open_gerber(str(rec['filename']))
  1818. break
  1819. basename = self.collection.get_names()[0]
  1820. isolate(basename, '-passes', '10', '-combine', '1')
  1821. iso = self.collection.get_by_name(basename + "_iso")
  1822. with wait_signal(self.new_object_available, to):
  1823. iso.generatecncjob()
  1824. # iso.generatecncjob()
  1825. # wait_signal2(self.new_object_available, to)
  1826. return str(self.collection.get_names())
  1827. except Exception as e:
  1828. return str(e)
  1829. def mytest2(*args):
  1830. to = int(args[0])
  1831. for rec in self.recent:
  1832. if rec['kind'] == 'gerber':
  1833. self.open_gerber(str(rec['filename']))
  1834. break
  1835. basename = self.collection.get_names()[0]
  1836. isolate(basename, '-passes', '10', '-combine', '1')
  1837. iso = self.collection.get_by_name(basename + "_iso")
  1838. with wait_signal(self.new_object_available, to):
  1839. 1/0 # Force exception
  1840. iso.generatecncjob()
  1841. return str(self.collection.get_names())
  1842. def mytest3(*args):
  1843. to = int(args[0])
  1844. def sometask(*args):
  1845. time.sleep(2)
  1846. self.inform.emit("mytest3")
  1847. with wait_signal(self.inform, to):
  1848. self.worker_task.emit({'fcn': sometask, 'params': []})
  1849. return "mytest3 done"
  1850. def mytest4(*args):
  1851. to = int(args[0])
  1852. def sometask(*args):
  1853. time.sleep(2)
  1854. 1/0 # Force exception
  1855. self.inform.emit("mytest4")
  1856. with wait_signal(self.inform, to):
  1857. self.worker_task.emit({'fcn': sometask, 'params': []})
  1858. return "mytest3 done"
  1859. def export_svg(name, filename, *args):
  1860. a, kwa = h(*args)
  1861. types = {'scale_factor': float}
  1862. for key in kwa:
  1863. if key not in types:
  1864. return 'Unknown parameter: %s' % key
  1865. kwa[key] = types[key](kwa[key])
  1866. self.export_svg(str(name), str(filename), **kwa)
  1867. def import_svg(filename, *args):
  1868. a, kwa = h(*args)
  1869. types = {'outname': str}
  1870. for key in kwa:
  1871. if key not in types:
  1872. return 'Unknown parameter: %s' % key
  1873. kwa[key] = types[key](kwa[key])
  1874. self.import_svg(str(filename), **kwa)
  1875. def open_gerber(filename, *args):
  1876. a, kwa = h(*args)
  1877. types = {'follow': bool,
  1878. 'outname': str}
  1879. for key in kwa:
  1880. if key not in types:
  1881. return 'Unknown parameter: %s' % key
  1882. kwa[key] = types[key](kwa[key])
  1883. self.open_gerber(str(filename), **kwa)
  1884. def open_excellon(filename, *args):
  1885. a, kwa = h(*args)
  1886. types = {'outname': str}
  1887. for key in kwa:
  1888. if key not in types:
  1889. return 'Unknown parameter: %s' % key
  1890. kwa[key] = types[key](kwa[key])
  1891. self.open_excellon(str(filename), **kwa)
  1892. def open_gcode(filename, *args):
  1893. a, kwa = h(*args)
  1894. types = {'outname': str}
  1895. for key in kwa:
  1896. if key not in types:
  1897. return 'Unknown parameter: %s' % key
  1898. kwa[key] = types[key](kwa[key])
  1899. self.open_gcode(str(filename), **kwa)
  1900. def cutout(name, *args):
  1901. a, kwa = h(*args)
  1902. types = {'dia': float,
  1903. 'margin': float,
  1904. 'gapsize': float,
  1905. 'gaps': str}
  1906. for key in kwa:
  1907. if key not in types:
  1908. return 'Unknown parameter: %s' % key
  1909. kwa[key] = types[key](kwa[key])
  1910. try:
  1911. obj = self.collection.get_by_name(str(name))
  1912. except:
  1913. return "Could not retrieve object: %s" % name
  1914. def geo_init_me(geo_obj, app_obj):
  1915. margin = kwa['margin']+kwa['dia']/2
  1916. gap_size = kwa['dia']+kwa['gapsize']
  1917. minx, miny, maxx, maxy = obj.bounds()
  1918. minx -= margin
  1919. maxx += margin
  1920. miny -= margin
  1921. maxy += margin
  1922. midx = 0.5 * (minx + maxx)
  1923. midy = 0.5 * (miny + maxy)
  1924. hgap = 0.5 * gap_size
  1925. pts = [[midx - hgap, maxy],
  1926. [minx, maxy],
  1927. [minx, midy + hgap],
  1928. [minx, midy - hgap],
  1929. [minx, miny],
  1930. [midx - hgap, miny],
  1931. [midx + hgap, miny],
  1932. [maxx, miny],
  1933. [maxx, midy - hgap],
  1934. [maxx, midy + hgap],
  1935. [maxx, maxy],
  1936. [midx + hgap, maxy]]
  1937. cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  1938. [pts[6], pts[7], pts[10], pts[11]]],
  1939. "lr": [[pts[9], pts[10], pts[1], pts[2]],
  1940. [pts[3], pts[4], pts[7], pts[8]]],
  1941. "4": [[pts[0], pts[1], pts[2]],
  1942. [pts[3], pts[4], pts[5]],
  1943. [pts[6], pts[7], pts[8]],
  1944. [pts[9], pts[10], pts[11]]]}
  1945. cuts = cases[kwa['gaps']]
  1946. geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  1947. try:
  1948. obj.app.new_object("geometry", name + "_cutout", geo_init_me)
  1949. except Exception, e:
  1950. return "Operation failed: %s" % str(e)
  1951. return 'Ok'
  1952. def geocutout(name, *args):
  1953. """
  1954. Subtract gaps from geometry, this will not create new object
  1955. :param name:
  1956. :param args:
  1957. :return:
  1958. """
  1959. a, kwa = h(*args)
  1960. types = {'dia': float,
  1961. 'gapsize': float,
  1962. 'gaps': str}
  1963. # How gaps wil be rendered:
  1964. # lr - left + right
  1965. # tb - top + bottom
  1966. # 4 - left + right +top + bottom
  1967. # 2lr - 2*left + 2*right
  1968. # 2tb - 2*top + 2*bottom
  1969. # 8 - 2*left + 2*right +2*top + 2*bottom
  1970. for key in kwa:
  1971. if key not in types:
  1972. return 'Unknown parameter: %s' % key
  1973. kwa[key] = types[key](kwa[key])
  1974. try:
  1975. obj = self.collection.get_by_name(str(name))
  1976. except:
  1977. return "Could not retrieve object: %s" % name
  1978. # Get min and max data for each object as we just cut rectangles across X or Y
  1979. xmin, ymin, xmax, ymax = obj.bounds()
  1980. px = 0.5 * (xmin + xmax)
  1981. py = 0.5 * (ymin + ymax)
  1982. lenghtx = (xmax - xmin)
  1983. lenghty = (ymax - ymin)
  1984. gapsize = kwa['gapsize'] + kwa['dia'] / 2
  1985. if kwa['gaps'] == '8' or kwa['gaps']=='2lr':
  1986. subtract_rectangle(name,
  1987. xmin - gapsize,
  1988. py - gapsize + lenghty / 4,
  1989. xmax + gapsize,
  1990. py + gapsize + lenghty / 4)
  1991. subtract_rectangle(name,
  1992. xmin-gapsize,
  1993. py - gapsize - lenghty / 4,
  1994. xmax + gapsize,
  1995. py + gapsize - lenghty / 4)
  1996. if kwa['gaps'] == '8' or kwa['gaps']=='2tb':
  1997. subtract_rectangle(name,
  1998. px - gapsize + lenghtx / 4,
  1999. ymin-gapsize,
  2000. px + gapsize + lenghtx / 4,
  2001. ymax + gapsize)
  2002. subtract_rectangle(name,
  2003. px - gapsize - lenghtx / 4,
  2004. ymin - gapsize,
  2005. px + gapsize - lenghtx / 4,
  2006. ymax + gapsize)
  2007. if kwa['gaps'] == '4' or kwa['gaps']=='lr':
  2008. subtract_rectangle(name,
  2009. xmin - gapsize,
  2010. py - gapsize,
  2011. xmax + gapsize,
  2012. py + gapsize)
  2013. if kwa['gaps'] == '4' or kwa['gaps']=='tb':
  2014. subtract_rectangle(name,
  2015. px - gapsize,
  2016. ymin - gapsize,
  2017. px + gapsize,
  2018. ymax + gapsize)
  2019. return 'Ok'
  2020. def mirror(name, *args):
  2021. a, kwa = h(*args)
  2022. types = {'box': str,
  2023. 'axis': str,
  2024. 'dist': float}
  2025. for key in kwa:
  2026. if key not in types:
  2027. return 'Unknown parameter: %s' % key
  2028. kwa[key] = types[key](kwa[key])
  2029. # Get source object.
  2030. try:
  2031. obj = self.collection.get_by_name(str(name))
  2032. except:
  2033. return "Could not retrieve object: %s" % name
  2034. if obj is None:
  2035. return "Object not found: %s" % name
  2036. if not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMExcellon):
  2037. return "ERROR: Only Gerber and Excellon objects can be mirrored."
  2038. # Axis
  2039. try:
  2040. axis = kwa['axis'].upper()
  2041. except KeyError:
  2042. return "ERROR: Specify -axis X or -axis Y"
  2043. # Box
  2044. if 'box' in kwa:
  2045. try:
  2046. box = self.collection.get_by_name(kwa['box'])
  2047. except:
  2048. return "Could not retrieve object box: %s" % kwa['box']
  2049. if box is None:
  2050. return "Object box not found: %s" % kwa['box']
  2051. try:
  2052. xmin, ymin, xmax, ymax = box.bounds()
  2053. px = 0.5 * (xmin + xmax)
  2054. py = 0.5 * (ymin + ymax)
  2055. obj.mirror(axis, [px, py])
  2056. obj.plot()
  2057. except Exception, e:
  2058. return "Operation failed: %s" % str(e)
  2059. else:
  2060. try:
  2061. dist = float(kwa['dist'])
  2062. except KeyError:
  2063. dist = 0.0
  2064. except ValueError:
  2065. return "Invalid distance: %s" % kwa['dist']
  2066. try:
  2067. obj.mirror(axis, [dist, dist])
  2068. obj.plot()
  2069. except Exception, e:
  2070. return "Operation failed: %s" % str(e)
  2071. return 'Ok'
  2072. def aligndrillgrid(outname, *args):
  2073. a, kwa = h(*args)
  2074. types = {'gridx': float,
  2075. 'gridy': float,
  2076. 'gridoffsetx': float,
  2077. 'gridoffsety': float,
  2078. 'columns':int,
  2079. 'rows':int,
  2080. 'dia': float
  2081. }
  2082. for key in kwa:
  2083. if key not in types:
  2084. return 'Unknown parameter: %s' % key
  2085. kwa[key] = types[key](kwa[key])
  2086. if 'columns' not in kwa or 'rows' not in kwa:
  2087. return "ERROR: Specify -columns and -rows"
  2088. if 'gridx' not in kwa or 'gridy' not in kwa:
  2089. return "ERROR: Specify -gridx and -gridy"
  2090. if 'dia' not in kwa:
  2091. return "ERROR: Specify -dia"
  2092. if 'gridoffsetx' not in kwa:
  2093. gridoffsetx=0
  2094. else:
  2095. gridoffsetx=kwa['gridoffsetx']
  2096. if 'gridoffsety' not in kwa:
  2097. gridoffsety=0
  2098. else:
  2099. gridoffsety=kwa['gridoffsety']
  2100. # Tools
  2101. tools = {"1": {"C": kwa['dia']}}
  2102. def aligndrillgrid_init_me(init_obj, app_obj):
  2103. drills = []
  2104. currenty=0
  2105. for row in range(kwa['rows']):
  2106. currentx=0
  2107. for col in range(kwa['columns']):
  2108. point = Point(currentx + gridoffsetx, currenty + gridoffsety)
  2109. drills.append({"point": point, "tool": "1"})
  2110. currentx = currentx + kwa['gridx']
  2111. currenty = currenty + kwa['gridy']
  2112. init_obj.tools = tools
  2113. init_obj.drills = drills
  2114. init_obj.create_geometry()
  2115. self.new_object("excellon", outname , aligndrillgrid_init_me)
  2116. def aligndrill(name, *args):
  2117. a, kwa = h(*args)
  2118. types = {'box': str,
  2119. 'axis': str,
  2120. 'holes': str,
  2121. 'grid': float,
  2122. 'minoffset': float,
  2123. 'gridoffset': float,
  2124. 'axisoffset': float,
  2125. 'dia': float,
  2126. 'dist': float}
  2127. for key in kwa:
  2128. if key not in types:
  2129. return 'Unknown parameter: %s' % key
  2130. kwa[key] = types[key](kwa[key])
  2131. # Get source object.
  2132. try:
  2133. obj = self.collection.get_by_name(str(name))
  2134. except:
  2135. return "Could not retrieve object: %s" % name
  2136. if obj is None:
  2137. return "Object not found: %s" % name
  2138. if not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMExcellon):
  2139. return "ERROR: Only Gerber, Geometry and Excellon objects can be used."
  2140. # Axis
  2141. try:
  2142. axis = kwa['axis'].upper()
  2143. except KeyError:
  2144. return "ERROR: Specify -axis X or -axis Y"
  2145. if not ('holes' in kwa or ('grid' in kwa and 'gridoffset' in kwa)):
  2146. return "ERROR: Specify -holes or -grid with -gridoffset "
  2147. if 'holes' in kwa:
  2148. try:
  2149. holes = eval("[" + kwa['holes'] + "]")
  2150. except KeyError:
  2151. return "ERROR: Wrong -holes format (X1,Y1),(X2,Y2)"
  2152. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  2153. # Tools
  2154. tools = {"1": {"C": kwa['dia']}}
  2155. def alligndrill_init_me(init_obj, app_obj):
  2156. drills = []
  2157. if 'holes' in kwa:
  2158. for hole in holes:
  2159. point = Point(hole)
  2160. point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py))
  2161. drills.append({"point": point, "tool": "1"})
  2162. drills.append({"point": point_mirror, "tool": "1"})
  2163. else:
  2164. if not 'box' in kwa:
  2165. return "ERROR: -grid can be used only for -box"
  2166. if 'axisoffset' in kwa:
  2167. axisoffset=kwa['axisoffset']
  2168. else:
  2169. axisoffset=0
  2170. # This will align hole to given aligngridoffset and minimal offset from pcb, based on selected axis
  2171. if axis == "X":
  2172. firstpoint = kwa['gridoffset']
  2173. while (xmin - kwa['minoffset']) < firstpoint:
  2174. firstpoint = firstpoint - kwa['grid']
  2175. lastpoint = kwa['gridoffset']
  2176. while (xmax + kwa['minoffset']) > lastpoint:
  2177. lastpoint = lastpoint + kwa['grid']
  2178. localHoles = (firstpoint, axisoffset), (lastpoint, axisoffset)
  2179. else:
  2180. firstpoint = kwa['gridoffset']
  2181. while (ymin - kwa['minoffset']) < firstpoint:
  2182. firstpoint = firstpoint - kwa['grid']
  2183. lastpoint = kwa['gridoffset']
  2184. while (ymax + kwa['minoffset']) > lastpoint:
  2185. lastpoint=lastpoint+kwa['grid']
  2186. localHoles = (axisoffset, firstpoint), (axisoffset, lastpoint)
  2187. for hole in localHoles:
  2188. point = Point(hole)
  2189. point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py))
  2190. drills.append({"point": point, "tool": "1"})
  2191. drills.append({"point": point_mirror, "tool": "1"})
  2192. init_obj.tools = tools
  2193. init_obj.drills = drills
  2194. init_obj.create_geometry()
  2195. # Box
  2196. if 'box' in kwa:
  2197. try:
  2198. box = self.collection.get_by_name(kwa['box'])
  2199. except:
  2200. return "Could not retrieve object box: %s" % kwa['box']
  2201. if box is None:
  2202. return "Object box not found: %s" % kwa['box']
  2203. try:
  2204. xmin, ymin, xmax, ymax = box.bounds()
  2205. px = 0.5 * (xmin + xmax)
  2206. py = 0.5 * (ymin + ymax)
  2207. obj.app.new_object("excellon", name + "_aligndrill", alligndrill_init_me)
  2208. except Exception, e:
  2209. return "Operation failed: %s" % str(e)
  2210. else:
  2211. try:
  2212. dist = float(kwa['dist'])
  2213. except KeyError:
  2214. dist = 0.0
  2215. except ValueError:
  2216. return "Invalid distance: %s" % kwa['dist']
  2217. try:
  2218. px=dist
  2219. py=dist
  2220. obj.app.new_object("excellon", name + "_alligndrill", alligndrill_init_me)
  2221. except Exception, e:
  2222. return "Operation failed: %s" % str(e)
  2223. return 'Ok'
  2224. def drillcncjob(name=None, *args):
  2225. '''
  2226. TCL shell command - see help section
  2227. :param name: name of object
  2228. :param args: array of arguments
  2229. :return: "Ok" if completed without errors
  2230. '''
  2231. a, kwa = h(*args)
  2232. types = {'tools': str,
  2233. 'outname': str,
  2234. 'drillz': float,
  2235. 'travelz': float,
  2236. 'feedrate': float,
  2237. 'spindlespeed': int,
  2238. 'toolchange': int
  2239. }
  2240. if name is None:
  2241. self.raiseTclError('Argument name is missing.')
  2242. for key in kwa:
  2243. if key not in types:
  2244. self.raiseTclError('Unknown parameter: %s' % key)
  2245. try:
  2246. kwa[key] = types[key](kwa[key])
  2247. except Exception, e:
  2248. self.raiseTclError("Cannot cast argument '%s' to type %s." % (key, str(types[key])))
  2249. try:
  2250. obj = self.collection.get_by_name(str(name))
  2251. except:
  2252. self.raiseTclError("Could not retrieve object: %s" % name)
  2253. if obj is None:
  2254. self.raiseTclError('Object not found: %s' % name)
  2255. if not isinstance(obj, FlatCAMExcellon):
  2256. self.raiseTclError('Only Excellon objects can be drilled, got %s %s.' % (name, type(obj)))
  2257. try:
  2258. # Get the tools from the list
  2259. job_name = kwa["outname"]
  2260. # Object initialization function for app.new_object()
  2261. def job_init(job_obj, app_obj):
  2262. job_obj.z_cut = kwa["drillz"]
  2263. job_obj.z_move = kwa["travelz"]
  2264. job_obj.feedrate = kwa["feedrate"]
  2265. job_obj.spindlespeed = kwa["spindlespeed"] if "spindlespeed" in kwa else None
  2266. toolchange = True if "toolchange" in kwa and kwa["toolchange"] == 1 else False
  2267. job_obj.generate_from_excellon_by_tool(obj, kwa["tools"], toolchange)
  2268. job_obj.gcode_parse()
  2269. job_obj.create_geometry()
  2270. obj.app.new_object("cncjob", job_name, job_init)
  2271. except Exception, e:
  2272. self.raiseTclError("Operation failed: %s" % str(e))
  2273. return 'Ok'
  2274. def millholes(name=None, *args):
  2275. '''
  2276. TCL shell command - see help section
  2277. :param name: name of object
  2278. :param args: array of arguments
  2279. :return: "Ok" if completed without errors
  2280. '''
  2281. a, kwa = h(*args)
  2282. types = {'tooldia': float,
  2283. 'tools': str,
  2284. 'outname': str}
  2285. if name is None:
  2286. self.raiseTclError('Argument name is missing.')
  2287. for key in kwa:
  2288. if key not in types:
  2289. self.raiseTclError('Unknown parameter: %s' % key)
  2290. try:
  2291. kwa[key] = types[key](kwa[key])
  2292. except Exception, e:
  2293. self.raiseTclError("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2294. try:
  2295. if 'tools' in kwa:
  2296. kwa['tools'] = [x.strip() for x in kwa['tools'].split(",")]
  2297. except Exception as e:
  2298. self.raiseTclError("Bad tools: %s" % str(e))
  2299. try:
  2300. obj = self.collection.get_by_name(str(name))
  2301. except:
  2302. self.raiseTclError("Could not retrieve object: %s" % name)
  2303. if obj is None:
  2304. self.raiseTclError("Object not found: %s" % name)
  2305. if not isinstance(obj, FlatCAMExcellon):
  2306. self.raiseTclError('Only Excellon objects can be mill drilled, got %s %s.' % (name, type(obj)))
  2307. try:
  2308. success, msg = obj.generate_milling(**kwa)
  2309. except Exception as e:
  2310. self.raiseTclError("Operation failed: %s" % str(e))
  2311. if not success:
  2312. self.raiseTclError(msg)
  2313. return 'Ok'
  2314. def exteriors(name=None, *args):
  2315. '''
  2316. TCL shell command - see help section
  2317. :param name: name of object
  2318. :param args: array of arguments
  2319. :return: "Ok" if completed without errors
  2320. '''
  2321. a, kwa = h(*args)
  2322. types = {'outname': str}
  2323. if name is None:
  2324. self.raiseTclError('Argument name is missing.')
  2325. for key in kwa:
  2326. if key not in types:
  2327. self.raiseTclError('Unknown parameter: %s' % key)
  2328. try:
  2329. kwa[key] = types[key](kwa[key])
  2330. except Exception, e:
  2331. self.raiseTclError("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2332. try:
  2333. obj = self.collection.get_by_name(str(name))
  2334. except:
  2335. self.raiseTclError("Could not retrieve object: %s" % name)
  2336. if obj is None:
  2337. self.raiseTclError("Object not found: %s" % name)
  2338. if not isinstance(obj, Geometry):
  2339. self.raiseTclError('Expected Geometry, got %s %s.' % (name, type(obj)))
  2340. def geo_init(geo_obj, app_obj):
  2341. geo_obj.solid_geometry = obj_exteriors
  2342. if 'outname' in kwa:
  2343. outname = kwa['outname']
  2344. else:
  2345. outname = name + ".exteriors"
  2346. try:
  2347. obj_exteriors = obj.get_exteriors()
  2348. self.new_object('geometry', outname, geo_init)
  2349. except Exception as e:
  2350. self.raiseTclError("Failed: %s" % str(e))
  2351. return 'Ok'
  2352. def interiors(name=None, *args):
  2353. '''
  2354. TCL shell command - see help section
  2355. :param name: name of object
  2356. :param args: array of arguments
  2357. :return: "Ok" if completed without errors
  2358. '''
  2359. a, kwa = h(*args)
  2360. types = {'outname': str}
  2361. for key in kwa:
  2362. if key not in types:
  2363. self.raiseTclError('Unknown parameter: %s' % key)
  2364. try:
  2365. kwa[key] = types[key](kwa[key])
  2366. except Exception, e:
  2367. self.raiseTclError("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2368. if name is None:
  2369. self.raiseTclError('Argument name is missing.')
  2370. try:
  2371. obj = self.collection.get_by_name(str(name))
  2372. except:
  2373. self.raiseTclError("Could not retrieve object: %s" % name)
  2374. if obj is None:
  2375. self.raiseTclError("Object not found: %s" % name)
  2376. if not isinstance(obj, Geometry):
  2377. self.raiseTclError('Expected Geometry, got %s %s.' % (name, type(obj)))
  2378. def geo_init(geo_obj, app_obj):
  2379. geo_obj.solid_geometry = obj_interiors
  2380. if 'outname' in kwa:
  2381. outname = kwa['outname']
  2382. else:
  2383. outname = name + ".interiors"
  2384. try:
  2385. obj_interiors = obj.get_interiors()
  2386. self.new_object('geometry', outname, geo_init)
  2387. except Exception as e:
  2388. self.raiseTclError("Failed: %s" % str(e))
  2389. return 'Ok'
  2390. def isolate(name=None, *args):
  2391. '''
  2392. TCL shell command - see help section
  2393. :param name: name of object
  2394. :param args: array of arguments
  2395. :return: "Ok" if completed without errors
  2396. '''
  2397. a, kwa = h(*args)
  2398. types = {'dia': float,
  2399. 'passes': int,
  2400. 'overlap': float,
  2401. 'outname': str,
  2402. 'combine': int}
  2403. for key in kwa:
  2404. if key not in types:
  2405. self.raiseTclError('Unknown parameter: %s' % key)
  2406. try:
  2407. kwa[key] = types[key](kwa[key])
  2408. except Exception, e:
  2409. self.raiseTclError("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2410. try:
  2411. obj = self.collection.get_by_name(str(name))
  2412. except:
  2413. self.raiseTclError("Could not retrieve object: %s" % name)
  2414. if obj is None:
  2415. self.raiseTclError("Object not found: %s" % name)
  2416. assert isinstance(obj, FlatCAMGerber), \
  2417. "Expected a FlatCAMGerber, got %s" % type(obj)
  2418. if not isinstance(obj, FlatCAMGerber):
  2419. self.raiseTclError('Expected FlatCAMGerber, got %s %s.' % (name, type(obj)))
  2420. try:
  2421. obj.isolate(**kwa)
  2422. except Exception, e:
  2423. self.raiseTclError("Operation failed: %s" % str(e))
  2424. return 'Ok'
  2425. def cncjob(obj_name, *args):
  2426. a, kwa = h(*args)
  2427. types = {'z_cut': float,
  2428. 'z_move': float,
  2429. 'feedrate': float,
  2430. 'tooldia': float,
  2431. 'outname': str,
  2432. 'spindlespeed': int,
  2433. 'multidepth' : bool,
  2434. 'depthperpass' : float
  2435. }
  2436. for key in kwa:
  2437. if key not in types:
  2438. return 'Unknown parameter: %s' % key
  2439. kwa[key] = types[key](kwa[key])
  2440. try:
  2441. obj = self.collection.get_by_name(str(obj_name))
  2442. except:
  2443. return "Could not retrieve object: %s" % obj_name
  2444. if obj is None:
  2445. return "Object not found: %s" % obj_name
  2446. try:
  2447. obj.generatecncjob(**kwa)
  2448. except Exception, e:
  2449. return "Operation failed: %s" % str(e)
  2450. return 'Ok'
  2451. def write_gcode(obj_name, filename, preamble='', postamble=''):
  2452. """
  2453. Requires obj_name to be available. It might still be in the
  2454. making at the time this function is called, so check for
  2455. promises and send to background if there are promises.
  2456. """
  2457. # If there are promised objects, wait until all promises have been fulfilled.
  2458. if self.collection.has_promises():
  2459. def write_gcode_on_object(new_object):
  2460. self.log.debug("write_gcode_on_object(): Disconnecting %s" % write_gcode_on_object)
  2461. self.new_object_available.disconnect(write_gcode_on_object)
  2462. write_gcode(obj_name, filename, preamble, postamble)
  2463. # Try again when a new object becomes available.
  2464. self.log.debug("write_gcode(): Collection has promises. Queued for %s." % obj_name)
  2465. self.log.debug("write_gcode(): Queued function: %s" % write_gcode_on_object)
  2466. self.new_object_available.connect(write_gcode_on_object)
  2467. return
  2468. self.log.debug("write_gcode(): No promises. Continuing for %s." % obj_name)
  2469. try:
  2470. obj = self.collection.get_by_name(str(obj_name))
  2471. except:
  2472. return "Could not retrieve object: %s" % obj_name
  2473. try:
  2474. obj.export_gcode(str(filename), str(preamble), str(postamble))
  2475. except Exception, e:
  2476. return "Operation failed: %s" % str(e)
  2477. def paint_poly(obj_name, inside_pt_x, inside_pt_y, tooldia, overlap):
  2478. try:
  2479. obj = self.collection.get_by_name(str(obj_name))
  2480. except:
  2481. return "Could not retrieve object: %s" % obj_name
  2482. if obj is None:
  2483. return "Object not found: %s" % obj_name
  2484. obj.paint_poly([float(inside_pt_x), float(inside_pt_y)], float(tooldia), float(overlap))
  2485. def add_poly(obj_name, *args):
  2486. if len(args) % 2 != 0:
  2487. return "Incomplete coordinate."
  2488. points = [[float(args[2*i]), float(args[2*i+1])] for i in range(len(args)/2)]
  2489. try:
  2490. obj = self.collection.get_by_name(str(obj_name))
  2491. except:
  2492. return "Could not retrieve object: %s" % obj_name
  2493. if obj is None:
  2494. return "Object not found: %s" % obj_name
  2495. obj.add_polygon(points)
  2496. def add_rectangle(obj_name, botleft_x, botleft_y, topright_x, topright_y):
  2497. return add_poly(obj_name, botleft_x, botleft_y, botleft_x, topright_y,
  2498. topright_x, topright_y, topright_x, botleft_y)
  2499. def subtract_poly(obj_name, *args):
  2500. if len(args) % 2 != 0:
  2501. return "Incomplete coordinate."
  2502. points = [[float(args[2*i]), float(args[2*i+1])] for i in range(len(args)/2)]
  2503. try:
  2504. obj = self.collection.get_by_name(str(obj_name))
  2505. except:
  2506. return "Could not retrieve object: %s" % obj_name
  2507. if obj is None:
  2508. return "Object not found: %s" % obj_name
  2509. obj.subtract_polygon(points)
  2510. obj.plot()
  2511. return "OK."
  2512. def subtract_rectangle(obj_name, botleft_x, botleft_y, topright_x, topright_y):
  2513. return subtract_poly(obj_name, botleft_x, botleft_y, botleft_x, topright_y,
  2514. topright_x, topright_y, topright_x, botleft_y)
  2515. def add_circle(obj_name, center_x, center_y, radius):
  2516. try:
  2517. obj = self.collection.get_by_name(str(obj_name))
  2518. except:
  2519. return "Could not retrieve object: %s" % obj_name
  2520. if obj is None:
  2521. return "Object not found: %s" % obj_name
  2522. obj.add_circle([float(center_x), float(center_y)], float(radius))
  2523. def set_active(obj_name):
  2524. try:
  2525. self.collection.set_active(str(obj_name))
  2526. except Exception, e:
  2527. return "Command failed: %s" % str(e)
  2528. def delete(obj_name):
  2529. try:
  2530. #deselect all to avoid delete selected object when run delete from shell
  2531. self.collection.set_all_inactive()
  2532. self.collection.set_active(str(obj_name))
  2533. self.on_delete()
  2534. except Exception, e:
  2535. return "Command failed: %s" % str(e)
  2536. def geo_union(obj_name):
  2537. try:
  2538. obj = self.collection.get_by_name(str(obj_name))
  2539. except:
  2540. return "Could not retrieve object: %s" % obj_name
  2541. if obj is None:
  2542. return "Object not found: %s" % obj_name
  2543. obj.union()
  2544. def join_geometries(obj_name, *obj_names):
  2545. objs = []
  2546. for obj_n in obj_names:
  2547. obj = self.collection.get_by_name(str(obj_n))
  2548. if obj is None:
  2549. return "Object not found: %s" % obj_n
  2550. else:
  2551. objs.append(obj)
  2552. def initialize(obj, app):
  2553. FlatCAMGeometry.merge(objs, obj)
  2554. if objs is not None:
  2555. self.new_object("geometry", obj_name, initialize)
  2556. def join_excellons(obj_name, *obj_names):
  2557. objs = []
  2558. for obj_n in obj_names:
  2559. obj = self.collection.get_by_name(str(obj_n))
  2560. if obj is None:
  2561. return "Object not found: %s" % obj_n
  2562. else:
  2563. objs.append(obj)
  2564. def initialize(obj, app):
  2565. FlatCAMExcellon.merge(objs, obj)
  2566. if objs is not None:
  2567. self.new_object("excellon", obj_name, initialize)
  2568. def panelize(name, *args):
  2569. a, kwa = h(*args)
  2570. types = {'box': str,
  2571. 'spacing_columns': float,
  2572. 'spacing_rows': float,
  2573. 'columns': int,
  2574. 'rows': int,
  2575. 'outname': str}
  2576. for key in kwa:
  2577. if key not in types:
  2578. return 'Unknown parameter: %s' % key
  2579. kwa[key] = types[key](kwa[key])
  2580. # Get source object.
  2581. try:
  2582. obj = self.collection.get_by_name(str(name))
  2583. except:
  2584. return "Could not retrieve object: %s" % name
  2585. if obj is None:
  2586. return "Object not found: %s" % name
  2587. if 'box' in kwa:
  2588. boxname=kwa['box']
  2589. try:
  2590. box = self.collection.get_by_name(boxname)
  2591. except:
  2592. return "Could not retrieve object: %s" % name
  2593. else:
  2594. box=obj
  2595. if 'columns' not in kwa or 'rows' not in kwa:
  2596. return "ERROR: Specify -columns and -rows"
  2597. if 'outname' in kwa:
  2598. outname=kwa['outname']
  2599. else:
  2600. outname=name+'_panelized'
  2601. if 'spacing_columns' in kwa:
  2602. spacing_columns=kwa['spacing_columns']
  2603. else:
  2604. spacing_columns=5
  2605. if 'spacing_rows' in kwa:
  2606. spacing_rows=kwa['spacing_rows']
  2607. else:
  2608. spacing_rows=5
  2609. xmin, ymin, xmax, ymax = box.bounds()
  2610. lenghtx = xmax-xmin+spacing_columns
  2611. lenghty = ymax-ymin+spacing_rows
  2612. currenty=0
  2613. def initialize_local(obj_init, app):
  2614. obj_init.solid_geometry = obj.solid_geometry
  2615. obj_init.offset([float(currentx), float(currenty)]),
  2616. def initialize_local_excellon(obj_init, app):
  2617. FlatCAMExcellon.merge(obj, obj_init)
  2618. obj_init.offset([float(currentx), float(currenty)]),
  2619. def initialize_geometry(obj_init, app):
  2620. FlatCAMGeometry.merge(objs, obj_init)
  2621. def initialize_excellon(obj_init, app):
  2622. FlatCAMExcellon.merge(objs, obj_init)
  2623. objs=[]
  2624. if obj is not None:
  2625. for row in range(kwa['rows']):
  2626. currentx=0
  2627. for col in range(kwa['columns']):
  2628. local_outname=outname+".tmp."+str(col)+"."+str(row)
  2629. if isinstance(obj, FlatCAMExcellon):
  2630. new_obj=self.new_object("excellon", local_outname, initialize_local_excellon)
  2631. else:
  2632. new_obj=self.new_object("geometry", local_outname, initialize_local)
  2633. objs.append(new_obj)
  2634. currentx=currentx+lenghtx
  2635. currenty=currenty+lenghty
  2636. if isinstance(obj, FlatCAMExcellon):
  2637. self.new_object("excellon", outname, initialize_excellon)
  2638. else:
  2639. self.new_object("geometry", outname, initialize_geometry)
  2640. #deselect all to avoid delete selected object when run delete from shell
  2641. self.collection.set_all_inactive()
  2642. for delobj in objs:
  2643. self.collection.set_active(delobj.options['name'])
  2644. self.on_delete()
  2645. else:
  2646. return "ERROR: obj is None"
  2647. return "Ok"
  2648. def make_docs():
  2649. output = ''
  2650. import collections
  2651. od = collections.OrderedDict(sorted(commands.items()))
  2652. for cmd, val in od.iteritems():
  2653. #print cmd, '\n', ''.join(['~']*len(cmd))
  2654. output += cmd + ' \n' + ''.join(['~'] * len(cmd)) + '\n'
  2655. t = val['help']
  2656. usage_i = t.find('>')
  2657. if usage_i < 0:
  2658. expl = t
  2659. #print expl + '\n'
  2660. output += expl + '\n\n'
  2661. continue
  2662. expl = t[:usage_i - 1]
  2663. #print expl + '\n'
  2664. output += expl + '\n\n'
  2665. end_usage_i = t[usage_i:].find('\n')
  2666. if end_usage_i < 0:
  2667. end_usage_i = len(t[usage_i:])
  2668. #print ' ' + t[usage_i:]
  2669. #print ' No parameters.\n'
  2670. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  2671. else:
  2672. extras = t[usage_i+end_usage_i+1:]
  2673. parts = [s.strip() for s in extras.split('\n')]
  2674. #print ' ' + t[usage_i:usage_i+end_usage_i]
  2675. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  2676. for p in parts:
  2677. #print ' ' + p + '\n'
  2678. output += ' ' + p + '\n\n'
  2679. return output
  2680. def follow(obj_name, *args):
  2681. a, kwa = h(*args)
  2682. types = {'outname': str}
  2683. for key in kwa:
  2684. if key not in types:
  2685. return 'Unknown parameter: %s' % key
  2686. kwa[key] = types[key](kwa[key])
  2687. try:
  2688. obj = self.collection.get_by_name(str(obj_name))
  2689. except:
  2690. return "Could not retrieve object: %s" % obj_name
  2691. if obj is None:
  2692. return "Object not found: %s" % obj_name
  2693. try:
  2694. obj.follow(**kwa)
  2695. except Exception, e:
  2696. return "ERROR: %s" % str(e)
  2697. def get_sys(param):
  2698. if param in self.defaults:
  2699. return self.defaults[param]
  2700. return "ERROR: No such system parameter."
  2701. def set_sys(param, value):
  2702. # tcl string to python keywords:
  2703. tcl2py = {
  2704. "None": None,
  2705. "none": None,
  2706. "false": False,
  2707. "False": False,
  2708. "true": True,
  2709. "True": True
  2710. }
  2711. if param in self.defaults:
  2712. try:
  2713. value = tcl2py[value]
  2714. except KeyError:
  2715. pass
  2716. self.defaults[param] = value
  2717. self.propagate_defaults()
  2718. return "Ok"
  2719. return "ERROR: No such system parameter."
  2720. '''
  2721. Howto implement TCL shell commands:
  2722. All parameters passed to command should be possible to set as None and test it afterwards.
  2723. This is because we need to see error caused in tcl,
  2724. if None value as default parameter is not allowed TCL will return empty error.
  2725. Use:
  2726. def mycommand(name=None,...):
  2727. Test it like this:
  2728. if name is None:
  2729. self.raiseTclError('Argument name is missing.')
  2730. When error ocurre, always use raiseTclError, never return "sometext" on error,
  2731. otherwise we will miss it and processing will silently continue.
  2732. Method raiseTclError pass error into TCL interpreter, then raise python exception,
  2733. which is catched in exec_command and displayed in TCL shell console with red background.
  2734. Error in console is displayed with TCL trace.
  2735. This behavior works only within main thread,
  2736. errors with promissed tasks can be catched and detected only with log.
  2737. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  2738. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  2739. '''
  2740. commands = {
  2741. 'mytest': {
  2742. 'fcn': mytest,
  2743. 'help': "Test function. Only for testing."
  2744. },
  2745. 'mytest2': {
  2746. 'fcn': mytest2,
  2747. 'help': "Test function. Only for testing."
  2748. },
  2749. 'mytest3': {
  2750. 'fcn': mytest3,
  2751. 'help': "Test function. Only for testing."
  2752. },
  2753. 'mytest4': {
  2754. 'fcn': mytest4,
  2755. 'help': "Test function. Only for testing."
  2756. },
  2757. 'help': {
  2758. 'fcn': shelp,
  2759. 'help': "Shows list of commands."
  2760. },
  2761. 'import_svg': {
  2762. 'fcn': import_svg,
  2763. 'help': "Import an SVG file as a Geometry Object.\n" +
  2764. "> import_svg <filename>" +
  2765. " filename: Path to the file to import."
  2766. },
  2767. 'export_svg': {
  2768. 'fcn': export_svg,
  2769. 'help': "Export a Geometry Object as a SVG File\n" +
  2770. "> export_svg <name> <filename> [-scale_factor <0.0 (float)>]\n" +
  2771. " name: Name of the geometry object to export.\n" +
  2772. " filename: Path to the file to export.\n" +
  2773. " scale_factor: Multiplication factor used for scaling line widths during export."
  2774. },
  2775. 'open_gerber': {
  2776. 'fcn': open_gerber,
  2777. 'help': "Opens a Gerber file.\n"
  2778. "> open_gerber <filename> [-follow <0|1>] [-outname <o>]\n"
  2779. " filename: Path to file to open.\n" +
  2780. " follow: If 1, does not create polygons, just follows the gerber path.\n" +
  2781. " outname: Name of the created gerber object."
  2782. },
  2783. 'open_excellon': {
  2784. 'fcn': open_excellon,
  2785. 'help': "Opens an Excellon file.\n" +
  2786. "> open_excellon <filename> [-outname <o>]\n" +
  2787. " filename: Path to file to open.\n" +
  2788. " outname: Name of the created excellon object."
  2789. },
  2790. 'open_gcode': {
  2791. 'fcn': open_gcode,
  2792. 'help': "Opens an G-Code file.\n" +
  2793. "> open_gcode <filename> [-outname <o>]\n" +
  2794. " filename: Path to file to open.\n" +
  2795. " outname: Name of the created CNC Job object."
  2796. },
  2797. 'open_project': {
  2798. 'fcn': self.open_project,
  2799. "help": "Opens a FlatCAM project.\n" +
  2800. "> open_project <filename>\n" +
  2801. " filename: Path to file to open."
  2802. },
  2803. 'save_project': {
  2804. 'fcn': self.save_project,
  2805. 'help': "Saves the FlatCAM project to file.\n" +
  2806. "> save_project <filename>\n" +
  2807. " filename: Path to file to save."
  2808. },
  2809. 'set_active': {
  2810. 'fcn': set_active,
  2811. 'help': "Sets a FlatCAM object as active.\n" +
  2812. "> set_active <name>\n" +
  2813. " name: Name of the object."
  2814. },
  2815. 'get_names': {
  2816. 'fcn': lambda: '\n'.join(self.collection.get_names()),
  2817. 'help': "Lists the names of objects in the project.\n" +
  2818. "> get_names"
  2819. },
  2820. 'new': {
  2821. 'fcn': self.on_file_new,
  2822. 'help': "Starts a new project. Clears objects from memory.\n" +
  2823. "> new"
  2824. },
  2825. 'options': {
  2826. 'fcn': options,
  2827. 'help': "Shows the settings for an object.\n" +
  2828. "> options <name>\n" +
  2829. " name: Object name."
  2830. },
  2831. 'isolate': {
  2832. 'fcn': isolate,
  2833. 'help': "Creates isolation routing geometry for the given Gerber.\n" +
  2834. "> isolate <name> [-dia <d>] [-passes <p>] [-overlap <o>] [-combine 0|1]\n" +
  2835. " name: Name of the object.\n"
  2836. " dia: Tool diameter\n passes: # of tool width.\n" +
  2837. " overlap: Fraction of tool diameter to overlap passes." +
  2838. " combine: combine all passes into one geometry." +
  2839. " outname: Name of the resulting Geometry object."
  2840. },
  2841. 'cutout': {
  2842. 'fcn': cutout,
  2843. 'help': "Creates board cutout.\n" +
  2844. "> cutout <name> [-dia <3.0 (float)>] [-margin <0.0 (float)>] [-gapsize <0.5 (float)>] [-gaps <lr (4|tb|lr)>]\n" +
  2845. " name: Name of the object\n" +
  2846. " dia: Tool diameter\n" +
  2847. " margin: Margin over bounds\n" +
  2848. " gapsize: size of gap\n" +
  2849. " gaps: type of gaps"
  2850. },
  2851. 'geocutout': {
  2852. 'fcn': geocutout,
  2853. 'help': "Cut holding gaps from geometry.\n" +
  2854. "> geocutout <name> [-dia <3.0 (float)>] [-margin <0.0 (float)>] [-gapsize <0.5 (float)>] [-gaps <lr (8|4|tb|lr|2tb|2lr)>]\n" +
  2855. " name: Name of the geometry object\n" +
  2856. " dia: Tool diameter\n" +
  2857. " margin: Margin over bounds\n" +
  2858. " gapsize: size of gap\n" +
  2859. " gaps: type of gaps\n" +
  2860. "\n" +
  2861. " example:\n" +
  2862. "\n" +
  2863. " #isolate margin for example from fritzing arduino shield or any svg etc\n" +
  2864. " isolate BCu_margin -dia 3 -overlap 1\n" +
  2865. "\n" +
  2866. " #create exteriors from isolated object\n" +
  2867. " exteriors BCu_margin_iso -outname BCu_margin_iso_exterior\n" +
  2868. "\n" +
  2869. " #delete isolated object if you dond need id anymore\n" +
  2870. " delete BCu_margin_iso\n" +
  2871. "\n" +
  2872. " #finally cut holding gaps\n" +
  2873. " geocutout BCu_margin_iso_exterior -dia 3 -gapsize 0.6 -gaps 4\n"
  2874. },
  2875. 'mirror': {
  2876. 'fcn': mirror,
  2877. 'help': "Mirror a layer.\n" +
  2878. "> mirror <name> -axis <X|Y> [-box <nameOfBox> | -dist <number>]\n" +
  2879. " name: Name of the object (Gerber or Excellon) to mirror.\n" +
  2880. " box: Name of object which act as box (cutout for example.)\n" +
  2881. " axis: Mirror axis parallel to the X or Y axis.\n" +
  2882. " dist: Distance of the mirror axis to the X or Y axis."
  2883. },
  2884. 'aligndrillgrid': {
  2885. 'fcn': aligndrillgrid,
  2886. 'help': "Create excellon with drills for aligment grid.\n" +
  2887. "> aligndrillgrid <outname> [-dia <3.0 (float)>] -gridx <float> [-gridoffsetx <0 (float)>] -gridy <float> [-gridoffsety <0 (float)>] -columns <int> -rows <int>\n" +
  2888. " outname: Name of the object to create.\n" +
  2889. " dia: Tool diameter\n" +
  2890. " gridx: grid size in X axis\n" +
  2891. " gridoffsetx: move grid from origin\n" +
  2892. " gridy: grid size in Y axis\n" +
  2893. " gridoffsety: move grid from origin\n" +
  2894. " colums: grid holes on X axis\n" +
  2895. " rows: grid holes on Y axis\n"
  2896. },
  2897. 'aligndrill': {
  2898. 'fcn': aligndrill,
  2899. 'help': "Create excellon with drills for aligment.\n" +
  2900. "> aligndrill <name> [-dia <3.0 (float)>] -axis <X|Y> [-box <nameOfBox> -minoffset <float> [-grid <10 (float)> -gridoffset <5 (float)> [-axisoffset <0 (float)>]] | -dist <number>]\n" +
  2901. " name: Name of the object (Gerber or Excellon) to mirror.\n" +
  2902. " dia: Tool diameter\n" +
  2903. " box: Name of object which act as box (cutout for example.)\n" +
  2904. " grid: aligning to grid, for thouse, who have aligning pins inside table in grid (-5,0),(5,0),(15,0)..." +
  2905. " gridoffset: offset of grid from 0 position" +
  2906. " minoffset: min and max distance between align hole and pcb" +
  2907. " axisoffset: offset on second axis before aligment holes" +
  2908. " axis: Mirror axis parallel to the X or Y axis.\n" +
  2909. " dist: Distance of the mirror axis to the X or Y axis."
  2910. },
  2911. 'exteriors': {
  2912. 'fcn': exteriors,
  2913. 'help': "Get exteriors of polygons.\n" +
  2914. "> exteriors <name> [-outname <outname>]\n" +
  2915. " name: Name of the source Geometry object.\n" +
  2916. " outname: Name of the resulting Geometry object."
  2917. },
  2918. 'interiors': {
  2919. 'fcn': interiors,
  2920. 'help': "Get interiors of polygons.\n" +
  2921. "> interiors <name> [-outname <outname>]\n" +
  2922. " name: Name of the source Geometry object.\n" +
  2923. " outname: Name of the resulting Geometry object."
  2924. },
  2925. 'drillcncjob': {
  2926. 'fcn': drillcncjob,
  2927. 'help': "Drill CNC job.\n" +
  2928. "> drillcncjob <name> -tools <str> -drillz <float> " +
  2929. "-travelz <float> -feedrate <float> -outname <str> " +
  2930. "[-spindlespeed (int)] [-toolchange (int)] \n" +
  2931. " name: Name of the object\n" +
  2932. " tools: Comma separated indexes of tools (example: 1,3 or 2)\n" +
  2933. " drillz: Drill depth into material (example: -2.0)\n" +
  2934. " travelz: Travel distance above material (example: 2.0)\n" +
  2935. " feedrate: Drilling feed rate\n" +
  2936. " outname: Name of object to create\n" +
  2937. " spindlespeed: Speed of the spindle in rpm (example: 4000)\n" +
  2938. " toolchange: Enable tool changes (example: 1)\n"
  2939. },
  2940. 'millholes': {
  2941. 'fcn': millholes,
  2942. 'help': "Create Geometry Object for milling holes from Excellon.\n" +
  2943. "> millholes <name> -tools <str> -tooldia <float> -outname <str> \n" +
  2944. " name: Name of the Excellon Object\n" +
  2945. " tools: Comma separated indexes of tools (example: 1,3 or 2)\n" +
  2946. " tooldia: Diameter of the milling tool (example: 0.1)\n" +
  2947. " outname: Name of object to create\n"
  2948. },
  2949. 'scale': {
  2950. 'fcn': lambda name, factor: self.collection.get_by_name(str(name)).scale(float(factor)),
  2951. 'help': "Resizes the object by a factor.\n" +
  2952. "> scale <name> <factor>\n" +
  2953. " name: Name of the object\n factor: Fraction by which to scale"
  2954. },
  2955. 'offset': {
  2956. 'fcn': lambda name, x, y: self.collection.get_by_name(str(name)).offset([float(x), float(y)]),
  2957. 'help': "Changes the position of the object.\n" +
  2958. "> offset <name> <x> <y>\n" +
  2959. " name: Name of the object\n" +
  2960. " x: X-axis distance\n" +
  2961. " y: Y-axis distance"
  2962. },
  2963. 'plot': {
  2964. 'fcn': self.plot_all,
  2965. 'help': 'Updates the plot on the user interface'
  2966. },
  2967. 'cncjob': {
  2968. 'fcn': cncjob,
  2969. 'help': 'Generates a CNC Job from a Geometry Object.\n' +
  2970. '> cncjob <name> [-z_cut <c>] [-z_move <float>] [-feedrate <float>] [-tooldia <float>] [-spindlespeed <int>] [-multidepth <bool>] [-depthperpass <float>] [-outname <str>]\n' +
  2971. ' name: Name of the source object\n' +
  2972. ' z_cut: Z-axis cutting position\n' +
  2973. ' z_move: Z-axis moving position\n' +
  2974. ' feedrate: Moving speed when cutting\n' +
  2975. ' tooldia: Tool diameter to show on screen\n' +
  2976. ' spindlespeed: Speed of the spindle in rpm (example: 4000)\n' +
  2977. ' multidepth: Use or not multidepth cnccut\n'+
  2978. ' depthperpass: Height of one layer for multidepth\n'+
  2979. ' outname: Name of the output object'
  2980. },
  2981. 'write_gcode': {
  2982. 'fcn': write_gcode,
  2983. 'help': 'Saves G-code of a CNC Job object to file.\n' +
  2984. '> write_gcode <name> <filename>\n' +
  2985. ' name: Source CNC Job object\n' +
  2986. ' filename: Output filename'
  2987. },
  2988. 'paint_poly': {
  2989. 'fcn': paint_poly,
  2990. 'help': 'Creates a geometry object with toolpath to cover the inside of a polygon.\n' +
  2991. '> paint_poly <name> <inside_pt_x> <inside_pt_y> <tooldia> <overlap>\n' +
  2992. ' name: Name of the sourge geometry object.\n' +
  2993. ' inside_pt_x, inside_pt_y: Coordinates of a point inside the polygon.\n' +
  2994. ' tooldia: Diameter of the tool to be used.\n' +
  2995. ' overlap: Fraction of the tool diameter to overlap cuts.'
  2996. },
  2997. 'new_geometry': {
  2998. 'fcn': lambda name: self.new_object('geometry', str(name), lambda x, y: None),
  2999. 'help': 'Creates a new empty geometry object.\n' +
  3000. '> new_geometry <name>\n' +
  3001. ' name: New object name'
  3002. },
  3003. 'add_poly': {
  3004. 'fcn': add_poly,
  3005. 'help': 'Creates a polygon in the given Geometry object.\n' +
  3006. '> create_poly <name> <x0> <y0> <x1> <y1> <x2> <y2> [x3 y3 [...]]\n' +
  3007. ' name: Name of the geometry object to which to append the polygon.\n' +
  3008. ' xi, yi: Coordinates of points in the polygon.'
  3009. },
  3010. 'subtract_poly': {
  3011. 'fcn': subtract_poly,
  3012. 'help': 'Subtract polygon from the given Geometry object.\n' +
  3013. '> subtract_poly <name> <x0> <y0> <x1> <y1> <x2> <y2> [x3 y3 [...]]\n' +
  3014. ' name: Name of the geometry object, which will be sutracted.\n' +
  3015. ' xi, yi: Coordinates of points in the polygon.'
  3016. },
  3017. 'delete': {
  3018. 'fcn': delete,
  3019. 'help': 'Deletes the give object.\n' +
  3020. '> delete <name>\n' +
  3021. ' name: Name of the object to delete.'
  3022. },
  3023. 'geo_union': {
  3024. 'fcn': geo_union,
  3025. 'help': 'Runs a union operation (addition) on the components ' +
  3026. 'of the geometry object. For example, if it contains ' +
  3027. '2 intersecting polygons, this opperation adds them into' +
  3028. 'a single larger polygon.\n' +
  3029. '> geo_union <name>\n' +
  3030. ' name: Name of the geometry object.'
  3031. },
  3032. 'join_geometries': {
  3033. 'fcn': join_geometries,
  3034. 'help': 'Runs a merge operation (join) on the geometry ' +
  3035. 'objects.' +
  3036. '> join_geometries <out_name> <obj_name_0>....\n' +
  3037. ' out_name: Name of the new geometry object.' +
  3038. ' obj_name_0... names of the objects to join'
  3039. },
  3040. 'join_excellons': {
  3041. 'fcn': join_excellons,
  3042. 'help': 'Runs a merge operation (join) on the excellon ' +
  3043. 'objects.' +
  3044. '> join_excellons <out_name> <obj_name_0>....\n' +
  3045. ' out_name: Name of the new excellon object.' +
  3046. ' obj_name_0... names of the objects to join'
  3047. },
  3048. 'panelize': {
  3049. 'fcn': panelize,
  3050. 'help': "Simple panelize geometries.\n" +
  3051. "> panelize <name> [-box <nameOfBox>] [-spacing_columns <5 (float)>] [-spacing_rows <5 (float)>] -columns <int> -rows <int> [-outname <n>]\n" +
  3052. " name: Name of the object to panelize.\n" +
  3053. " box: Name of object which act as box (cutout for example.) for cutout boundary. Object from name is used if not specified.\n" +
  3054. " spacing_columns: spacing between columns\n"+
  3055. " spacing_rows: spacing between rows\n"+
  3056. " columns: number of columns\n"+
  3057. " rows: number of rows\n"+
  3058. " outname: Name of the new geometry object."
  3059. },
  3060. 'subtract_rect': {
  3061. 'fcn': subtract_rectangle,
  3062. 'help': 'Subtract rectange from the given Geometry object.\n' +
  3063. '> subtract_rect <name> <botleft_x> <botleft_y> <topright_x> <topright_y>\n' +
  3064. ' name: Name of the geometry object, which will be subtracted.\n' +
  3065. ' botleft_x, botleft_y: Coordinates of the bottom left corner.\n' +
  3066. ' topright_x, topright_y Coordinates of the top right corner.'
  3067. },
  3068. 'add_rect': {
  3069. 'fcn': add_rectangle,
  3070. 'help': 'Creates a rectange in the given Geometry object.\n' +
  3071. '> add_rect <name> <botleft_x> <botleft_y> <topright_x> <topright_y>\n' +
  3072. ' name: Name of the geometry object to which to append the rectangle.\n' +
  3073. ' botleft_x, botleft_y: Coordinates of the bottom left corner.\n' +
  3074. ' topright_x, topright_y Coordinates of the top right corner.'
  3075. },
  3076. 'add_circle': {
  3077. 'fcn': add_circle,
  3078. 'help': 'Creates a circle in the given Geometry object.\n' +
  3079. '> add_circle <name> <center_x> <center_y> <radius>\n' +
  3080. ' name: Name of the geometry object to which to append the circle.\n' +
  3081. ' center_x, center_y: Coordinates of the center of the circle.\n' +
  3082. ' radius: Radius of the circle.'
  3083. },
  3084. 'make_docs': {
  3085. 'fcn': make_docs,
  3086. 'help': 'Prints command rererence in reStructuredText format.'
  3087. },
  3088. 'follow': {
  3089. 'fcn': follow,
  3090. 'help': 'Creates a geometry object following gerber paths.\n' +
  3091. '> follow <name> [-outname <oname>]\n' +
  3092. ' name: Name of the gerber object.\n' +
  3093. ' outname: Name of the output geometry object.'
  3094. },
  3095. 'get_sys': {
  3096. 'fcn': get_sys,
  3097. 'help': 'Get the value of a system parameter (FlatCAM constant)\n' +
  3098. '> get_sys <sysparam>\n' +
  3099. ' sysparam: Name of the parameter.'
  3100. },
  3101. 'set_sys': {
  3102. 'fcn': set_sys,
  3103. 'help': 'Set the value of a system parameter (FlatCAM constant)\n' +
  3104. '> set_sys <sysparam> <paramvalue>\n' +
  3105. ' sysparam: Name of the parameter.\n' +
  3106. ' paramvalue: Value to set.'
  3107. }
  3108. }
  3109. # Add commands to the tcl interpreter
  3110. for cmd in commands:
  3111. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  3112. # Make the tcl puts function return instead of print to stdout
  3113. self.tcl.eval('''
  3114. rename puts original_puts
  3115. proc puts {args} {
  3116. if {[llength $args] == 1} {
  3117. return "[lindex $args 0]"
  3118. } else {
  3119. eval original_puts $args
  3120. }
  3121. }
  3122. ''')
  3123. def setup_recent_items(self):
  3124. self.log.debug("setup_recent_items()")
  3125. # TODO: Move this to constructor
  3126. icons = {
  3127. "gerber": "share/flatcam_icon16.png",
  3128. "excellon": "share/drill16.png",
  3129. "cncjob": "share/cnc16.png",
  3130. "project": "share/project16.png",
  3131. "svg": "share/geometry16.png"
  3132. }
  3133. openers = {
  3134. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  3135. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  3136. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  3137. 'project': self.open_project,
  3138. 'svg': self.import_svg
  3139. }
  3140. # Open file
  3141. try:
  3142. f = open(self.data_path + '/recent.json')
  3143. except IOError:
  3144. App.log.error("Failed to load recent item list.")
  3145. self.inform.emit("[error] Failed to load recent item list.")
  3146. return
  3147. try:
  3148. self.recent = json.load(f)
  3149. except json.scanner.JSONDecodeError:
  3150. App.log.error("Failed to parse recent item list.")
  3151. self.inform.emit("[error] Failed to parse recent item list.")
  3152. f.close()
  3153. return
  3154. f.close()
  3155. # Closure needed to create callbacks in a loop.
  3156. # Otherwise late binding occurs.
  3157. def make_callback(func, fname):
  3158. def opener():
  3159. func(fname)
  3160. return opener
  3161. # Reset menu
  3162. self.ui.recent.clear()
  3163. # Create menu items
  3164. for recent in self.recent:
  3165. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  3166. try:
  3167. action = QtGui.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  3168. # Attach callback
  3169. o = make_callback(openers[recent["kind"]], recent['filename'])
  3170. action.triggered.connect(o)
  3171. self.ui.recent.addAction(action)
  3172. except KeyError:
  3173. App.log.error("Unsupported file type: %s" % recent["kind"])
  3174. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  3175. # self.ui.menufilerecent.set_submenu(recent_menu)
  3176. # recent_menu.show_all()
  3177. # self.ui.recent.show()
  3178. def setup_component_editor(self):
  3179. label = QtGui.QLabel("Choose an item from Project")
  3180. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  3181. self.ui.selected_scroll_area.setWidget(label)
  3182. def setup_obj_classes(self):
  3183. """
  3184. Sets up application specifics on the FlatCAMObj class.
  3185. :return: None
  3186. """
  3187. FlatCAMObj.app = self
  3188. FCProcess.app = self
  3189. FCProcessContainer.app = self
  3190. def version_check(self):
  3191. """
  3192. Checks for the latest version of the program. Alerts the
  3193. user if theirs is outdated. This method is meant to be run
  3194. in a separate thread.
  3195. :return: None
  3196. """
  3197. self.log.debug("version_check()")
  3198. full_url = App.version_url + \
  3199. "?s=" + str(self.defaults['serial']) + \
  3200. "&v=" + str(self.version) + \
  3201. "&os=" + str(self.os) + \
  3202. "&" + urllib.urlencode(self.defaults["stats"])
  3203. App.log.debug("Checking for updates @ %s" % full_url)
  3204. ### Get the data
  3205. try:
  3206. f = urllib.urlopen(full_url)
  3207. except:
  3208. # App.log.warning("Failed checking for latest version. Could not connect.")
  3209. self.log.warning("Failed checking for latest version. Could not connect.")
  3210. self.inform.emit("[warning] Failed checking for latest version. Could not connect.")
  3211. return
  3212. try:
  3213. data = json.load(f)
  3214. except Exception, e:
  3215. App.log.error("Could not parse information about latest version.")
  3216. self.inform.emit("[error] Could not parse information about latest version.")
  3217. App.log.debug("json.load(): %s" % str(e))
  3218. f.close()
  3219. return
  3220. f.close()
  3221. ### Latest version?
  3222. if self.version >= data["version"]:
  3223. App.log.debug("FlatCAM is up to date!")
  3224. self.inform.emit("[success] FlatCAM is up to date!")
  3225. return
  3226. App.log.debug("Newer version available.")
  3227. self.message.emit(
  3228. "Newer Version Available",
  3229. QtCore.QString("There is a newer version of FlatCAM " +
  3230. "available for download:<br><br>" +
  3231. "<B>" + data["name"] + "</b><br>" +
  3232. data["message"].replace("\n", "<br>")),
  3233. "info"
  3234. )
  3235. def enable_all_plots(self, *args):
  3236. self.plotcanvas.clear()
  3237. def worker_task(app_obj):
  3238. percentage = 0.1
  3239. try:
  3240. delta = 0.9 / len(self.collection.get_list())
  3241. except ZeroDivisionError:
  3242. self.progress.emit(0)
  3243. return
  3244. for obj in self.collection.get_list():
  3245. obj.options['plot'] = True
  3246. obj.plot()
  3247. percentage += delta
  3248. self.progress.emit(int(percentage*100))
  3249. self.progress.emit(0)
  3250. self.plots_updated.emit()
  3251. # Send to worker
  3252. # self.worker.add_task(worker_task, [self])
  3253. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  3254. def save_project(self, filename):
  3255. """
  3256. Saves the current project to the specified file.
  3257. :param filename: Name of the file in which to save.
  3258. :type filename: str
  3259. :return: None
  3260. """
  3261. self.log.debug("save_project()")
  3262. ## Capture the latest changes
  3263. # Current object
  3264. try:
  3265. self.collection.get_active().read_form()
  3266. except:
  3267. self.log.debug("[warning] There was no active object")
  3268. pass
  3269. # Project options
  3270. self.options_read_form()
  3271. # Serialize the whole project
  3272. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  3273. "options": self.options,
  3274. "version": self.version}
  3275. # Open file
  3276. try:
  3277. f = open(filename, 'w')
  3278. except IOError:
  3279. App.log.error("[error] Failed to open file for saving: %s", filename)
  3280. return
  3281. # Write
  3282. json.dump(d, f, default=to_dict)
  3283. # try:
  3284. # json.dump(d, f, default=to_dict)
  3285. # except Exception, e:
  3286. # print str(e)
  3287. # App.log.error("[error] File open but failed to write: %s", filename)
  3288. # f.close()
  3289. # return
  3290. f.close()
  3291. self.inform.emit("Project saved to: %s" % filename)
  3292. # def main():
  3293. #
  3294. # app = QtGui.QApplication(sys.argv)
  3295. # fc = App()
  3296. # sys.exit(app.exec_())
  3297. #
  3298. #
  3299. # if __name__ == '__main__':
  3300. # main()