FlatCAMApp.py 177 KB

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