FlatCAMApp.py 168 KB

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