FlatCAMApp.py 169 KB

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