FlatCAMApp.py 166 KB

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