FlatCAMObj.py 235 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707
  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 copy
  9. import inspect # TODO: For debugging only.
  10. from datetime import datetime
  11. from flatcamGUI.ObjectUI import *
  12. from FlatCAMCommon import LoudDict
  13. from camlib import *
  14. import itertools
  15. import gettext
  16. import FlatCAMTranslation as fcTranslate
  17. fcTranslate.apply_language('strings')
  18. import builtins
  19. if '_' not in builtins.__dict__:
  20. _ = gettext.gettext
  21. class ObjectDeleted(Exception):
  22. # Interrupts plotting process if FlatCAMObj has been deleted
  23. pass
  24. class ValidationError(Exception):
  25. def __init__(self, message, errors):
  26. super().__init__(message)
  27. self.errors = errors
  28. ########################################
  29. ## FlatCAMObj ##
  30. ########################################
  31. class FlatCAMObj(QtCore.QObject):
  32. """
  33. Base type of objects handled in FlatCAM. These become interactive
  34. in the GUI, can be plotted, and their options can be modified
  35. by the user in their respective forms.
  36. """
  37. # Instance of the application to which these are related.
  38. # The app should set this value.
  39. app = None
  40. def __init__(self, name):
  41. """
  42. Constructor.
  43. :param name: Name of the object given by the user.
  44. :return: FlatCAMObj
  45. """
  46. QtCore.QObject.__init__(self)
  47. # View
  48. self.ui = None
  49. self.options = LoudDict(name=name)
  50. self.options.set_change_callback(self.on_options_change)
  51. self.form_fields = {}
  52. self.kind = None # Override with proper name
  53. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.vispy_canvas.view.scene)
  54. self.shapes = self.app.plotcanvas.new_shape_group()
  55. # self.mark_shapes = self.app.plotcanvas.new_shape_collection(layers=2)
  56. self.mark_shapes = {}
  57. self.item = None # Link with project view item
  58. self.muted_ui = False
  59. self.deleted = False
  60. try:
  61. self._drawing_tolerance = float(self.app.defaults["global_tolerance"]) if \
  62. self.app.defaults["global_tolerance"] else 0.01
  63. except ValueError:
  64. self._drawing_tolerance = 0.01
  65. self.isHovering = False
  66. self.notHovering = True
  67. # assert isinstance(self.ui, ObjectUI)
  68. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  69. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  70. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  71. def __del__(self):
  72. pass
  73. def __str__(self):
  74. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  75. def from_dict(self, d):
  76. """
  77. This supersedes ``from_dict`` in derived classes. Derived classes
  78. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  79. ``self.options`` is only updated, not overwritten. This ensures that
  80. options set by the app do not vanish when reading the objects
  81. from a project file.
  82. :param d: Dictionary with attributes to set.
  83. :return: None
  84. """
  85. for attr in self.ser_attrs:
  86. if attr == 'options':
  87. self.options.update(d[attr])
  88. else:
  89. try:
  90. setattr(self, attr, d[attr])
  91. except KeyError:
  92. log.debug("FlatCAMObj.from_dict() --> KeyError: %s. Means that we are loading an old project that don't"
  93. "have all attributes in the latest FlatCAM." % str(attr))
  94. pass
  95. def on_options_change(self, key):
  96. # Update form on programmatically options change
  97. self.set_form_item(key)
  98. # Set object visibility
  99. if key == 'plot':
  100. self.visible = self.options['plot']
  101. # self.emit(QtCore.SIGNAL("optionChanged"), key)
  102. self.optionChanged.emit(key)
  103. def set_ui(self, ui):
  104. self.ui = ui
  105. self.form_fields = {"name": self.ui.name_entry}
  106. assert isinstance(self.ui, ObjectUI)
  107. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  108. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  109. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  110. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  111. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  112. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  113. def build_ui(self):
  114. """
  115. Sets up the UI/form for this object. Show the UI
  116. in the App.
  117. :return: None
  118. :rtype: None
  119. """
  120. self.muted_ui = True
  121. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  122. # Remove anything else in the box
  123. # box_children = self.app.ui.notebook.selected_contents.get_children()
  124. # for child in box_children:
  125. # self.app.ui.notebook.selected_contents.remove(child)
  126. # while self.app.ui.selected_layout.count():
  127. # self.app.ui.selected_layout.takeAt(0)
  128. # Put in the UI
  129. # box_selected.pack_start(sw, True, True, 0)
  130. # self.app.ui.notebook.selected_contents.add(self.ui)
  131. # self.app.ui.selected_layout.addWidget(self.ui)
  132. try:
  133. self.app.ui.selected_scroll_area.takeWidget()
  134. except:
  135. self.app.log.debug("Nothing to remove")
  136. self.app.ui.selected_scroll_area.setWidget(self.ui)
  137. self.muted_ui = False
  138. def on_name_activate(self):
  139. old_name = copy(self.options["name"])
  140. new_name = self.ui.name_entry.get_value()
  141. if new_name != old_name:
  142. # update the SHELL auto-completer model data
  143. try:
  144. self.app.myKeywords.remove(old_name)
  145. self.app.myKeywords.append(new_name)
  146. self.app.shell._edit.set_model_data(self.app.myKeywords)
  147. self.app.ui.code_editor.set_model_data(self.app.myKeywords)
  148. except:
  149. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  150. self.options["name"] = self.ui.name_entry.get_value()
  151. self.app.inform.emit(_("[success] Name changed from {old} to {new}").format(old=old_name, new=new_name))
  152. def on_offset_button_click(self):
  153. self.app.report_usage("obj_on_offset_button")
  154. self.read_form()
  155. vect = self.ui.offsetvector_entry.get_value()
  156. self.offset(vect)
  157. self.plot()
  158. self.app.object_changed.emit(self)
  159. def on_scale_button_click(self):
  160. self.app.report_usage("obj_on_scale_button")
  161. self.read_form()
  162. factor = self.ui.scale_entry.get_value()
  163. self.scale(factor)
  164. self.plot()
  165. self.app.object_changed.emit(self)
  166. def on_skew_button_click(self):
  167. self.app.report_usage("obj_on_skew_button")
  168. self.read_form()
  169. xangle = self.ui.xangle_entry.get_value()
  170. yangle = self.ui.yangle_entry.get_value()
  171. self.skew(xangle, yangle)
  172. self.plot()
  173. self.app.object_changed.emit(self)
  174. def to_form(self):
  175. """
  176. Copies options to the UI form.
  177. :return: None
  178. """
  179. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  180. for option in self.options:
  181. try:
  182. self.set_form_item(option)
  183. except:
  184. self.app.log.warning("Unexpected error:", sys.exc_info())
  185. def read_form(self):
  186. """
  187. Reads form into ``self.options``.
  188. :return: None
  189. :rtype: None
  190. """
  191. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  192. for option in self.options:
  193. try:
  194. self.read_form_item(option)
  195. except:
  196. self.app.log.warning("Unexpected error:", sys.exc_info())
  197. def set_form_item(self, option):
  198. """
  199. Copies the specified option to the UI form.
  200. :param option: Name of the option (Key in ``self.options``).
  201. :type option: str
  202. :return: None
  203. """
  204. try:
  205. self.form_fields[option].set_value(self.options[option])
  206. except KeyError:
  207. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  208. pass
  209. def read_form_item(self, option):
  210. """
  211. Reads the specified option from the UI form into ``self.options``.
  212. :param option: Name of the option.
  213. :type option: str
  214. :return: None
  215. """
  216. try:
  217. self.options[option] = self.form_fields[option].get_value()
  218. except KeyError:
  219. self.app.log.warning("Failed to read option from field: %s" % option)
  220. def plot(self):
  221. """
  222. Plot this object (Extend this method to implement the actual plotting).
  223. Call this in descendants before doing the plotting.
  224. :return: Whether to continue plotting or not depending on the "plot" option.
  225. :rtype: bool
  226. """
  227. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  228. if self.deleted:
  229. return False
  230. self.clear()
  231. return True
  232. def serialize(self):
  233. """
  234. Returns a representation of the object as a dictionary so
  235. it can be later exported as JSON. Override this method.
  236. :return: Dictionary representing the object
  237. :rtype: dict
  238. """
  239. return
  240. def deserialize(self, obj_dict):
  241. """
  242. Re-builds an object from its serialized version.
  243. :param obj_dict: Dictionary representing a FlatCAMObj
  244. :type obj_dict: dict
  245. :return: None
  246. """
  247. return
  248. def add_shape(self, **kwargs):
  249. if self.deleted:
  250. raise ObjectDeleted()
  251. else:
  252. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  253. return key
  254. def add_mark_shape(self, apid, **kwargs):
  255. if self.deleted:
  256. raise ObjectDeleted()
  257. else:
  258. key = self.mark_shapes[apid].add(tolerance=self.drawing_tolerance, **kwargs)
  259. return key
  260. @property
  261. def visible(self):
  262. return self.shapes.visible
  263. @visible.setter
  264. def visible(self, value):
  265. self.shapes.visible = value
  266. # Not all object types has annotations
  267. try:
  268. self.annotation.visible = value
  269. except AttributeError:
  270. pass
  271. @property
  272. def drawing_tolerance(self):
  273. return self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  274. @drawing_tolerance.setter
  275. def drawing_tolerance(self, value):
  276. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  277. def clear(self, update=False):
  278. self.shapes.clear(update)
  279. # Not all object types has annotations
  280. try:
  281. self.annotation.clear(update)
  282. except AttributeError:
  283. pass
  284. # Not all object types have mark_shapes
  285. # try:
  286. # self.mark_shapes.clear(update)
  287. # except AttributeError:
  288. # pass
  289. def delete(self):
  290. # Free resources
  291. del self.ui
  292. del self.options
  293. # Set flag
  294. self.deleted = True
  295. class FlatCAMGerber(FlatCAMObj, Gerber):
  296. """
  297. Represents Gerber code.
  298. """
  299. optionChanged = QtCore.pyqtSignal(str)
  300. replotApertures = QtCore.pyqtSignal()
  301. ui_type = GerberObjectUI
  302. @staticmethod
  303. def merge(grb_list, grb_final):
  304. """
  305. Merges the geometry of objects in geo_list into
  306. the geometry of geo_final.
  307. :param grb_list: List of FlatCAMGerber Objects to join.
  308. :param grb_final: Destination FlatCAMGeometry object.
  309. :return: None
  310. """
  311. if grb_final.solid_geometry is None:
  312. grb_final.solid_geometry = []
  313. grb_final.follow_geometry = []
  314. if not grb_final.apertures:
  315. grb_final.apertures = {}
  316. if type(grb_final.solid_geometry) is not list:
  317. grb_final.solid_geometry = [grb_final.solid_geometry]
  318. grb_final.follow_geometry = [grb_final.follow_geometry]
  319. for grb in grb_list:
  320. # Expand lists
  321. if type(grb) is list:
  322. FlatCAMGerber.merge(grb, grb_final)
  323. else: # If not list, just append
  324. for option in grb.options:
  325. if option is not 'name':
  326. try:
  327. grb_final.options[option] = grb.options[option]
  328. except:
  329. log.warning("Failed to copy option.", option)
  330. try:
  331. for geos in grb.solid_geometry:
  332. grb_final.solid_geometry.append(geos)
  333. grb_final.follow_geometry.append(geos)
  334. except TypeError:
  335. grb_final.solid_geometry.append(grb.solid_geometry)
  336. grb_final.follow_geometry.append(grb.solid_geometry)
  337. for ap in grb.apertures:
  338. if ap not in grb_final.apertures:
  339. grb_final.apertures[ap] = grb.apertures[ap]
  340. else:
  341. # create a list of integers out of the grb.apertures keys and find the max of that value
  342. # then, the aperture duplicate is assigned an id value incremented with 1,
  343. # and finally made string because the apertures dict keys are strings
  344. max_ap = str(max([int(k) for k in grb_final.apertures.keys()]) + 1)
  345. grb_final.apertures[max_ap] = {}
  346. grb_final.apertures[max_ap]['solid_geometry'] = []
  347. for k, v in grb.apertures[ap].items():
  348. grb_final.apertures[max_ap][k] = v
  349. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  350. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  351. def __init__(self, name):
  352. Gerber.__init__(self, steps_per_circle=int(self.app.defaults["gerber_circle_steps"]))
  353. FlatCAMObj.__init__(self, name)
  354. self.kind = "gerber"
  355. # The 'name' is already in self.options from FlatCAMObj
  356. # Automatically updates the UI
  357. self.options.update({
  358. "plot": True,
  359. "multicolored": False,
  360. "solid": False,
  361. "isotooldia": 0.016,
  362. "isopasses": 1,
  363. "isooverlap": 0.15,
  364. "milling_type": "cl",
  365. "combine_passes": True,
  366. "noncoppermargin": 0.0,
  367. "noncopperrounded": False,
  368. "bboxmargin": 0.0,
  369. "bboxrounded": False,
  370. "aperture_display": False,
  371. "follow": False
  372. })
  373. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  374. self.iso_type = 2
  375. self.multigeo = False
  376. self.follow = False
  377. self.apertures_row = 0
  378. # store the source file here
  379. self.source_file = ""
  380. # list of rows with apertures plotted
  381. self.marked_rows = []
  382. # Attributes to be included in serialization
  383. # Always append to it because it carries contents
  384. # from predecessors.
  385. self.ser_attrs += ['options', 'kind']
  386. def set_ui(self, ui):
  387. """
  388. Maps options with GUI inputs.
  389. Connects GUI events to methods.
  390. :param ui: GUI object.
  391. :type ui: GerberObjectUI
  392. :return: None
  393. """
  394. FlatCAMObj.set_ui(self, ui)
  395. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  396. self.replotApertures.connect(self.on_mark_cb_click_table)
  397. self.form_fields.update({
  398. "plot": self.ui.plot_cb,
  399. "multicolored": self.ui.multicolored_cb,
  400. "solid": self.ui.solid_cb,
  401. "isotooldia": self.ui.iso_tool_dia_entry,
  402. "isopasses": self.ui.iso_width_entry,
  403. "isooverlap": self.ui.iso_overlap_entry,
  404. "milling_type": self.ui.milling_type_radio,
  405. "combine_passes": self.ui.combine_passes_cb,
  406. "noncoppermargin": self.ui.noncopper_margin_entry,
  407. "noncopperrounded": self.ui.noncopper_rounded_cb,
  408. "bboxmargin": self.ui.bbmargin_entry,
  409. "bboxrounded": self.ui.bbrounded_cb,
  410. "aperture_display": self.ui.aperture_table_visibility_cb,
  411. "follow": self.ui.follow_cb
  412. })
  413. # Fill form fields only on object create
  414. self.to_form()
  415. assert isinstance(self.ui, GerberObjectUI)
  416. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  417. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  418. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  419. self.ui.generate_ext_iso_button.clicked.connect(self.on_ext_iso_button_click)
  420. self.ui.generate_int_iso_button.clicked.connect(self.on_int_iso_button_click)
  421. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  422. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  423. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  424. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  425. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  426. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  427. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  428. # Show/Hide Advanced Options
  429. if self.app.defaults["global_app_level"] == 'b':
  430. self.ui.level.setText(_(
  431. '<span style="color:green;"><b>Basic</b></span>'
  432. ))
  433. self.ui.apertures_table_label.hide()
  434. self.ui.aperture_table_visibility_cb.hide()
  435. self.ui.milling_type_label.hide()
  436. self.ui.milling_type_radio.hide()
  437. self.ui.generate_ext_iso_button.hide()
  438. self.ui.generate_int_iso_button.hide()
  439. self.ui.follow_cb.hide()
  440. self.ui.padding_area_label.show()
  441. else:
  442. self.ui.level.setText(_(
  443. '<span style="color:red;"><b>Advanced</b></span>'
  444. ))
  445. self.ui.padding_area_label.hide()
  446. # add the shapes storage for marking apertures
  447. for ap_code in self.apertures:
  448. self.mark_shapes[ap_code] = self.app.plotcanvas.new_shape_collection(layers=2)
  449. # set initial state of the aperture table and associated widgets
  450. self.on_aperture_table_visibility_change()
  451. self.build_ui()
  452. def build_ui(self):
  453. FlatCAMObj.build_ui(self)
  454. try:
  455. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  456. self.ui.apertures_table.itemChanged.disconnect()
  457. except:
  458. pass
  459. self.apertures_row = 0
  460. aper_no = self.apertures_row + 1
  461. sort = []
  462. for k, v in list(self.apertures.items()):
  463. sort.append(int(k))
  464. sorted_apertures = sorted(sort)
  465. sort = []
  466. for k, v in list(self.aperture_macros.items()):
  467. sort.append(k)
  468. sorted_macros = sorted(sort)
  469. n = len(sorted_apertures) + len(sorted_macros)
  470. self.ui.apertures_table.setRowCount(n)
  471. for ap_code in sorted_apertures:
  472. ap_code = str(ap_code)
  473. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  474. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  475. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  476. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  477. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  478. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  479. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  480. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  481. ap_dim_item = QtWidgets.QTableWidgetItem(
  482. '%.4f, %.4f' % (self.apertures[ap_code]['width'] * self.file_units_factor,
  483. self.apertures[ap_code]['height'] * self.file_units_factor
  484. )
  485. )
  486. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  487. elif str(self.apertures[ap_code]['type']) == 'P':
  488. ap_dim_item = QtWidgets.QTableWidgetItem(
  489. '%.4f, %.4f' % (self.apertures[ap_code]['diam'] * self.file_units_factor,
  490. self.apertures[ap_code]['nVertices'] * self.file_units_factor)
  491. )
  492. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  493. else:
  494. ap_dim_item = QtWidgets.QTableWidgetItem('')
  495. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  496. try:
  497. if self.apertures[ap_code]['size'] is not None:
  498. ap_size_item = QtWidgets.QTableWidgetItem('%.4f' %
  499. float(self.apertures[ap_code]['size'] *
  500. self.file_units_factor))
  501. else:
  502. ap_size_item = QtWidgets.QTableWidgetItem('')
  503. except KeyError:
  504. ap_size_item = QtWidgets.QTableWidgetItem('')
  505. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  506. mark_item = FCCheckBox()
  507. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  508. # if self.ui.aperture_table_visibility_cb.isChecked():
  509. # mark_item.setChecked(True)
  510. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  511. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  512. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  513. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  514. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  515. self.apertures_row += 1
  516. for ap_code in sorted_macros:
  517. ap_code = str(ap_code)
  518. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  519. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  520. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  521. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  522. ap_type_item = QtWidgets.QTableWidgetItem('AM')
  523. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  524. mark_item = FCCheckBox()
  525. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  526. # if self.ui.aperture_table_visibility_cb.isChecked():
  527. # mark_item.setChecked(True)
  528. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  529. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  530. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  531. self.apertures_row += 1
  532. self.ui.apertures_table.selectColumn(0)
  533. self.ui.apertures_table.resizeColumnsToContents()
  534. self.ui.apertures_table.resizeRowsToContents()
  535. vertical_header = self.ui.apertures_table.verticalHeader()
  536. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  537. vertical_header.hide()
  538. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  539. horizontal_header = self.ui.apertures_table.horizontalHeader()
  540. horizontal_header.setMinimumSectionSize(10)
  541. horizontal_header.setDefaultSectionSize(70)
  542. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  543. horizontal_header.resizeSection(0, 20)
  544. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  545. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  546. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  547. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  548. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  549. horizontal_header.resizeSection(5, 17)
  550. self.ui.apertures_table.setColumnWidth(5, 17)
  551. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  552. self.ui.apertures_table.setSortingEnabled(False)
  553. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  554. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  555. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  556. if self.marked_rows:
  557. for row in range(self.ui.apertures_table.rowCount()):
  558. try:
  559. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  560. except IndexError:
  561. pass
  562. self.ui_connect()
  563. def ui_connect(self):
  564. for row in range(self.ui.apertures_table.rowCount()):
  565. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  566. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  567. def ui_disconnect(self):
  568. for row in range(self.ui.apertures_table.rowCount()):
  569. try:
  570. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  571. except:
  572. pass
  573. try:
  574. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  575. except:
  576. pass
  577. def on_generatenoncopper_button_click(self, *args):
  578. self.app.report_usage("gerber_on_generatenoncopper_button")
  579. self.read_form()
  580. name = self.options["name"] + "_noncopper"
  581. def geo_init(geo_obj, app_obj):
  582. assert isinstance(geo_obj, FlatCAMGeometry)
  583. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  584. if not self.options["noncopperrounded"]:
  585. bounding_box = bounding_box.envelope
  586. non_copper = bounding_box.difference(self.solid_geometry)
  587. geo_obj.solid_geometry = non_copper
  588. # TODO: Check for None
  589. self.app.new_object("geometry", name, geo_init)
  590. def on_generatebb_button_click(self, *args):
  591. self.app.report_usage("gerber_on_generatebb_button")
  592. self.read_form()
  593. name = self.options["name"] + "_bbox"
  594. def geo_init(geo_obj, app_obj):
  595. assert isinstance(geo_obj, FlatCAMGeometry)
  596. # Bounding box with rounded corners
  597. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  598. if not self.options["bboxrounded"]: # Remove rounded corners
  599. bounding_box = bounding_box.envelope
  600. geo_obj.solid_geometry = bounding_box
  601. self.app.new_object("geometry", name, geo_init)
  602. def on_ext_iso_button_click(self, *args):
  603. if self.ui.follow_cb.get_value() == True:
  604. obj = self.app.collection.get_active()
  605. obj.follow()
  606. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  607. obj.ui.plot_cb.toggle()
  608. else:
  609. self.app.report_usage("gerber_on_iso_button")
  610. self.read_form()
  611. self.isolate(iso_type=0)
  612. def on_int_iso_button_click(self, *args):
  613. if self.ui.follow_cb.get_value() is True:
  614. obj = self.app.collection.get_active()
  615. obj.follow()
  616. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  617. obj.ui.plot_cb.toggle()
  618. else:
  619. self.app.report_usage("gerber_on_iso_button")
  620. self.read_form()
  621. self.isolate(iso_type=1)
  622. def on_iso_button_click(self, *args):
  623. if self.ui.follow_cb.get_value() is True:
  624. obj = self.app.collection.get_active()
  625. obj.follow_geo()
  626. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  627. obj.ui.plot_cb.toggle()
  628. else:
  629. self.app.report_usage("gerber_on_iso_button")
  630. self.read_form()
  631. self.isolate()
  632. def follow_geo(self, outname=None):
  633. """
  634. Creates a geometry object "following" the gerber paths.
  635. :return: None
  636. """
  637. # default_name = self.options["name"] + "_follow"
  638. # follow_name = outname or default_name
  639. if outname is None:
  640. follow_name = self.options["name"] + "_follow"
  641. else:
  642. follow_name = outname
  643. def follow_init(follow_obj, app):
  644. # Propagate options
  645. follow_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  646. follow_obj.solid_geometry = self.follow_geometry
  647. # TODO: Do something if this is None. Offer changing name?
  648. try:
  649. self.app.new_object("geometry", follow_name, follow_init)
  650. except Exception as e:
  651. return "Operation failed: %s" % str(e)
  652. def isolate(self, iso_type=None, dia=None, passes=None, overlap=None,
  653. outname=None, combine=None, milling_type=None, follow=None):
  654. """
  655. Creates an isolation routing geometry object in the project.
  656. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  657. :param dia: Tool diameter
  658. :param passes: Number of tool widths to cut
  659. :param overlap: Overlap between passes in fraction of tool diameter
  660. :param outname: Base name of the output object
  661. :return: None
  662. """
  663. if dia is None:
  664. dia = float(self.options["isotooldia"])
  665. if passes is None:
  666. passes = int(self.options["isopasses"])
  667. if overlap is None:
  668. overlap = float(self.options["isooverlap"])
  669. if combine is None:
  670. combine = self.options["combine_passes"]
  671. else:
  672. combine = bool(combine)
  673. if milling_type is None:
  674. milling_type = self.options["milling_type"]
  675. if iso_type is None:
  676. self.iso_type = 2
  677. else:
  678. self.iso_type = iso_type
  679. base_name = self.options["name"] + "_iso"
  680. base_name = outname or base_name
  681. def generate_envelope(offset, invert, envelope_iso_type=2, follow=None):
  682. # isolation_geometry produces an envelope that is going on the left of the geometry
  683. # (the copper features). To leave the least amount of burrs on the features
  684. # the tool needs to travel on the right side of the features (this is called conventional milling)
  685. # the first pass is the one cutting all of the features, so it needs to be reversed
  686. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  687. # to cut on the right side of the left over copper i.e on the left side of the features.
  688. try:
  689. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  690. except Exception as e:
  691. log.debug(str(e))
  692. return 'fail'
  693. if invert:
  694. try:
  695. if type(geom) is MultiPolygon:
  696. pl = []
  697. for p in geom:
  698. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  699. geom = MultiPolygon(pl)
  700. elif type(geom) is Polygon:
  701. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  702. else:
  703. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry")
  704. except Exception as e:
  705. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  706. return geom
  707. if combine:
  708. if self.iso_type == 0:
  709. iso_name = self.options["name"] + "_ext_iso"
  710. elif self.iso_type == 1:
  711. iso_name = self.options["name"] + "_int_iso"
  712. else:
  713. iso_name = base_name
  714. # TODO: This is ugly. Create way to pass data into init function.
  715. def iso_init(geo_obj, app_obj):
  716. # Propagate options
  717. geo_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  718. geo_obj.solid_geometry = []
  719. for i in range(passes):
  720. iso_offset = (((2 * i + 1) / 2.0) * dia) - (i * overlap * dia)
  721. # if milling type is climb then the move is counter-clockwise around features
  722. if milling_type == 'cl':
  723. # geom = generate_envelope (offset, i == 0)
  724. geom = generate_envelope(iso_offset, 1, envelope_iso_type=self.iso_type, follow=follow)
  725. else:
  726. geom = generate_envelope(iso_offset, 0, envelope_iso_type=self.iso_type, follow=follow)
  727. geo_obj.solid_geometry.append(geom)
  728. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  729. # or just looking in the lists (they are one level depth) and if any is not empty
  730. # proceed with object creation, if there are empty and the number of them is the length
  731. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  732. empty_cnt = 0
  733. if not isinstance(geo_obj.solid_geometry, list):
  734. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  735. for g in geo_obj.solid_geometry:
  736. if g:
  737. app_obj.inform.emit(_(
  738. "[success] Isolation geometry created: %s"
  739. ) % geo_obj.options["name"])
  740. break
  741. else:
  742. empty_cnt += 1
  743. if empty_cnt == len(geo_obj.solid_geometry):
  744. raise ValidationError("Empty Geometry", None)
  745. geo_obj.multigeo = False
  746. # TODO: Do something if this is None. Offer changing name?
  747. self.app.new_object("geometry", iso_name, iso_init)
  748. else:
  749. for i in range(passes):
  750. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  751. if passes > 1:
  752. if self.iso_type == 0:
  753. iso_name = self.options["name"] + "_ext_iso" + str(i + 1)
  754. elif self.iso_type == 1:
  755. iso_name = self.options["name"] + "_int_iso" + str(i + 1)
  756. else:
  757. iso_name = base_name + str(i + 1)
  758. else:
  759. if self.iso_type == 0:
  760. iso_name = self.options["name"] + "_ext_iso"
  761. elif self.iso_type == 1:
  762. iso_name = self.options["name"] + "_int_iso"
  763. else:
  764. iso_name = base_name
  765. # TODO: This is ugly. Create way to pass data into init function.
  766. def iso_init(geo_obj, app_obj):
  767. # Propagate options
  768. geo_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  769. # if milling type is climb then the move is counter-clockwise around features
  770. if milling_type == 'cl':
  771. # geo_obj.solid_geometry = generate_envelope(offset, i == 0)
  772. geo_obj.solid_geometry = generate_envelope(offset, 1, envelope_iso_type=self.iso_type,
  773. follow=follow)
  774. else:
  775. geo_obj.solid_geometry = generate_envelope(offset, 0, envelope_iso_type=self.iso_type,
  776. follow=follow)
  777. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  778. # or just looking in the lists (they are one level depth) and if any is not empty
  779. # proceed with object creation, if there are empty and the number of them is the length
  780. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  781. empty_cnt = 0
  782. if not isinstance(geo_obj.solid_geometry, list):
  783. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  784. for g in geo_obj.solid_geometry:
  785. if g:
  786. app_obj.inform.emit(_(
  787. "[success] Isolation geometry created: %s"
  788. ) % geo_obj.options["name"])
  789. break
  790. else:
  791. empty_cnt += 1
  792. if empty_cnt == len(geo_obj.solid_geometry):
  793. raise ValidationError("Empty Geometry", None)
  794. geo_obj.multigeo = False
  795. # TODO: Do something if this is None. Offer changing name?
  796. self.app.new_object("geometry", iso_name, iso_init)
  797. def on_plot_cb_click(self, *args):
  798. if self.muted_ui:
  799. return
  800. self.read_form_item('plot')
  801. self.plot()
  802. def on_solid_cb_click(self, *args):
  803. if self.muted_ui:
  804. return
  805. self.read_form_item('solid')
  806. self.plot()
  807. def on_multicolored_cb_click(self, *args):
  808. if self.muted_ui:
  809. return
  810. self.read_form_item('multicolored')
  811. self.plot()
  812. def on_follow_cb_click(self):
  813. if self.muted_ui:
  814. return
  815. self.plot()
  816. def on_aperture_table_visibility_change(self):
  817. if self.ui.aperture_table_visibility_cb.isChecked():
  818. self.ui.apertures_table.setVisible(True)
  819. for ap in self.mark_shapes:
  820. self.mark_shapes[ap].enabled = True
  821. self.ui.mark_all_cb.setVisible(True)
  822. self.ui.mark_all_cb.setChecked(False)
  823. else:
  824. self.ui.apertures_table.setVisible(False)
  825. self.ui.mark_all_cb.setVisible(False)
  826. # on hide disable all mark plots
  827. for row in range(self.ui.apertures_table.rowCount()):
  828. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  829. self.clear_plot_apertures()
  830. for ap in self.mark_shapes:
  831. self.mark_shapes[ap].enabled = False
  832. def convert_units(self, units):
  833. """
  834. Converts the units of the object by scaling dimensions in all geometry
  835. and options.
  836. :param units: Units to which to convert the object: "IN" or "MM".
  837. :type units: str
  838. :return: None
  839. :rtype: None
  840. """
  841. factor = Gerber.convert_units(self, units)
  842. self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  843. self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  844. def plot(self, **kwargs):
  845. """
  846. :param kwargs: color and face_color
  847. :return:
  848. """
  849. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  850. # Does all the required setup and returns False
  851. # if the 'ptint' option is set to False.
  852. if not FlatCAMObj.plot(self):
  853. return
  854. if 'color' in kwargs:
  855. color = kwargs['color']
  856. else:
  857. color = self.app.defaults['global_plot_line']
  858. if 'face_color' in kwargs:
  859. face_color = kwargs['face_color']
  860. else:
  861. face_color = self.app.defaults['global_plot_fill']
  862. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  863. if self.ui.follow_cb.get_value():
  864. geometry = self.follow_geometry
  865. else:
  866. geometry = self.solid_geometry
  867. # Make sure geometry is iterable.
  868. try:
  869. _ = iter(geometry)
  870. except TypeError:
  871. geometry = [geometry]
  872. def random_color():
  873. color = np.random.rand(4)
  874. color[3] = 1
  875. return color
  876. try:
  877. if self.options["solid"]:
  878. for g in geometry:
  879. if type(g) == Polygon or type(g) == LineString:
  880. self.add_shape(shape=g, color=color,
  881. face_color=random_color() if self.options['multicolored']
  882. else face_color, visible=self.options['plot'])
  883. elif type(g) == Point:
  884. pass
  885. else:
  886. for el in g:
  887. self.add_shape(shape=el, color=color,
  888. face_color=random_color() if self.options['multicolored']
  889. else face_color, visible=self.options['plot'])
  890. else:
  891. for g in geometry:
  892. if type(g) == Polygon or type(g) == LineString:
  893. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  894. visible=self.options['plot'])
  895. elif type(g) == Point:
  896. pass
  897. else:
  898. for el in g:
  899. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  900. visible=self.options['plot'])
  901. self.shapes.redraw()
  902. except (ObjectDeleted, AttributeError):
  903. self.shapes.clear(update=True)
  904. # experimental plot() when the solid_geometry is stored in the self.apertures
  905. def plot_aperture(self, **kwargs):
  906. """
  907. :param kwargs: color and face_color
  908. :return:
  909. """
  910. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot_aperture()")
  911. # Does all the required setup and returns False
  912. # if the 'ptint' option is set to False.
  913. if not FlatCAMObj.plot(self):
  914. return
  915. # for marking apertures, line color and fill color are the same
  916. if 'color' in kwargs:
  917. color = kwargs['color']
  918. else:
  919. color = self.app.defaults['global_plot_fill']
  920. if 'marked_aperture' not in kwargs:
  921. return
  922. else:
  923. aperture_to_plot_mark = kwargs['marked_aperture']
  924. if aperture_to_plot_mark is None:
  925. return
  926. if 'visible' not in kwargs:
  927. visibility = True
  928. else:
  929. visibility = kwargs['visible']
  930. with self.app.proc_container.new(_("Plotting Apertures")) as proc:
  931. self.app.progress.emit(30)
  932. def job_thread(app_obj):
  933. self.app.progress.emit(30)
  934. try:
  935. if aperture_to_plot_mark in self.apertures:
  936. if type(self.apertures[aperture_to_plot_mark]['solid_geometry']) is not list:
  937. self.apertures[aperture_to_plot_mark]['solid_geometry'] = \
  938. [self.apertures[aperture_to_plot_mark]['solid_geometry']]
  939. for geo in self.apertures[aperture_to_plot_mark]['solid_geometry']:
  940. if type(geo) == Polygon or type(geo) == LineString:
  941. self.add_mark_shape(apid=aperture_to_plot_mark, shape=geo, color=color,
  942. face_color=color, visible=visibility)
  943. else:
  944. for el in geo:
  945. self.add_mark_shape(apid=aperture_to_plot_mark, shape=el, color=color,
  946. face_color=color, visible=visibility)
  947. self.mark_shapes[aperture_to_plot_mark].redraw()
  948. self.app.progress.emit(100)
  949. except (ObjectDeleted, AttributeError):
  950. self.clear_plot_apertures()
  951. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  952. def clear_plot_apertures(self, aperture='all'):
  953. """
  954. :param aperture: string; aperture for which to clear the mark shapes
  955. :return:
  956. """
  957. if aperture == 'all':
  958. for apid in self.apertures:
  959. self.mark_shapes[apid].clear(update=True)
  960. else:
  961. self.mark_shapes[aperture].clear(update=True)
  962. def clear_mark_all(self):
  963. self.ui.mark_all_cb.set_value(False)
  964. self.marked_rows[:] = []
  965. def on_mark_cb_click_table(self):
  966. """
  967. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  968. :return:
  969. """
  970. self.ui_disconnect()
  971. cw = self.sender()
  972. try:
  973. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  974. cw_row = cw_index.row()
  975. except AttributeError:
  976. cw_row = 0
  977. self.marked_rows[:] = []
  978. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  979. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  980. self.marked_rows.append(True)
  981. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  982. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'], marked_aperture=aperture, visible=True)
  983. self.mark_shapes[aperture].redraw()
  984. else:
  985. self.marked_rows.append(False)
  986. self.clear_plot_apertures(aperture=aperture)
  987. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  988. # if all the row mark's are enabled also enable the Mark All checkbox
  989. cb_cnt = 0
  990. total_row = self.ui.apertures_table.rowCount()
  991. for row in range(total_row):
  992. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  993. cb_cnt += 1
  994. else:
  995. cb_cnt -= 1
  996. if cb_cnt < total_row:
  997. self.ui.mark_all_cb.setChecked(False)
  998. else:
  999. self.ui.mark_all_cb.setChecked(True)
  1000. self.ui_connect()
  1001. def on_mark_all_click(self, signal):
  1002. self.ui_disconnect()
  1003. mark_all = self.ui.mark_all_cb.isChecked()
  1004. for row in range(self.ui.apertures_table.rowCount()):
  1005. # update the mark_rows list
  1006. if mark_all:
  1007. self.marked_rows.append(True)
  1008. else:
  1009. self.marked_rows[:] = []
  1010. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  1011. mark_cb.setChecked(mark_all)
  1012. if mark_all:
  1013. for aperture in self.apertures:
  1014. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1015. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'],
  1016. marked_aperture=aperture, visible=True)
  1017. # HACK: enable/disable the grid for a better look
  1018. self.app.ui.grid_snap_btn.trigger()
  1019. self.app.ui.grid_snap_btn.trigger()
  1020. else:
  1021. self.clear_plot_apertures()
  1022. self.ui_connect()
  1023. def mirror(self, axis, point):
  1024. Gerber.mirror(self, axis=axis, point=point)
  1025. self.replotApertures.emit()
  1026. def offset(self, vect):
  1027. Gerber.offset(self, vect=vect)
  1028. self.replotApertures.emit()
  1029. def rotate(self, angle, point):
  1030. Gerber.rotate(self, angle=angle, point=point)
  1031. self.replotApertures.emit()
  1032. def scale(self, xfactor, yfactor=None, point=None):
  1033. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  1034. self.replotApertures.emit()
  1035. def skew(self, angle_x, angle_y, point):
  1036. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1037. self.replotApertures.emit()
  1038. def serialize(self):
  1039. return {
  1040. "options": self.options,
  1041. "kind": self.kind
  1042. }
  1043. class FlatCAMExcellon(FlatCAMObj, Excellon):
  1044. """
  1045. Represents Excellon/Drill code.
  1046. """
  1047. ui_type = ExcellonObjectUI
  1048. optionChanged = QtCore.pyqtSignal(str)
  1049. def __init__(self, name):
  1050. Excellon.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  1051. FlatCAMObj.__init__(self, name)
  1052. self.kind = "excellon"
  1053. self.options.update({
  1054. "plot": True,
  1055. "solid": False,
  1056. "drillz": -0.1,
  1057. "travelz": 0.1,
  1058. "feedrate": 5.0,
  1059. "feedrate_rapid": 5.0,
  1060. "tooldia": 0.1,
  1061. "slot_tooldia": 0.1,
  1062. "toolchange": False,
  1063. "toolchangez": 1.0,
  1064. "toolchangexy": "0.0, 0.0",
  1065. "endz": 2.0,
  1066. "startz": None,
  1067. "spindlespeed": None,
  1068. "dwell": True,
  1069. "dwelltime": 1000,
  1070. "ppname_e": 'defaults',
  1071. "z_pdepth": -0.02,
  1072. "feedrate_probe": 3.0,
  1073. "optimization_type": "R",
  1074. "gcode_type": "drills"
  1075. })
  1076. # TODO: Document this.
  1077. self.tool_cbs = {}
  1078. # dict to hold the tool number as key and tool offset as value
  1079. self.tool_offset ={}
  1080. # variable to store the total amount of drills per job
  1081. self.tot_drill_cnt = 0
  1082. self.tool_row = 0
  1083. # variable to store the total amount of slots per job
  1084. self.tot_slot_cnt = 0
  1085. self.tool_row_slots = 0
  1086. # variable to store the distance travelled
  1087. self.travel_distance = 0.0
  1088. # store the source file here
  1089. self.source_file = ""
  1090. self.multigeo = True
  1091. # Attributes to be included in serialization
  1092. # Always append to it because it carries contents
  1093. # from predecessors.
  1094. self.ser_attrs += ['options', 'kind']
  1095. @staticmethod
  1096. def merge(exc_list, exc_final):
  1097. """
  1098. Merge Excellon objects found in exc_list parameter into exc_final object.
  1099. Options are always copied from source .
  1100. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  1101. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  1102. tool_name to be used in the final Excellon object, exc_final.
  1103. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  1104. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  1105. :param exc_final: Destination FlatCAMExcellon object.
  1106. :return: None
  1107. """
  1108. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  1109. flag_order = False
  1110. try:
  1111. flattened_list = list(itertools.chain(*exc_list))
  1112. except TypeError:
  1113. flattened_list = exc_list
  1114. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1115. # values will be list of Shapely Points; for drills
  1116. custom_dict_drills = {}
  1117. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1118. # values will be list of Shapely Points; for slots
  1119. custom_dict_slots = {}
  1120. for exc in flattened_list:
  1121. # copy options of the current excellon obj to the final excellon obj
  1122. for option in exc.options:
  1123. if option is not 'name':
  1124. try:
  1125. exc_final.options[option] = exc.options[option]
  1126. except:
  1127. exc.app.log.warning("Failed to copy option.", option)
  1128. for drill in exc.drills:
  1129. exc_tool_dia = float('%.3f' % exc.tools[drill['tool']]['C'])
  1130. if exc_tool_dia not in custom_dict_drills:
  1131. custom_dict_drills[exc_tool_dia] = [drill['point']]
  1132. else:
  1133. custom_dict_drills[exc_tool_dia].append(drill['point'])
  1134. for slot in exc.slots:
  1135. exc_tool_dia = float('%.3f' % exc.tools[slot['tool']]['C'])
  1136. if exc_tool_dia not in custom_dict_slots:
  1137. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  1138. else:
  1139. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  1140. # add the zeros and units to the exc_final object
  1141. exc_final.zeros = exc.zeros
  1142. exc_final.units = exc.units
  1143. # variable to make tool_name for the tools
  1144. current_tool = 0
  1145. # Here we add data to the exc_final object
  1146. # the tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  1147. # drills
  1148. for tool_dia in custom_dict_drills:
  1149. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  1150. current_tool += 1
  1151. tool_name = str(current_tool)
  1152. spec = {"C": float(tool_dia)}
  1153. exc_final.tools[tool_name] = spec
  1154. # rebuild the drills list of dict's that belong to the exc_final object
  1155. for point in custom_dict_drills[tool_dia]:
  1156. exc_final.drills.append(
  1157. {
  1158. "point": point,
  1159. "tool": str(current_tool)
  1160. }
  1161. )
  1162. # Here we add data to the exc_final object
  1163. # the tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  1164. # of two Shapely Points in case of slots
  1165. for tool_dia in custom_dict_slots:
  1166. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  1167. # but only if there are no drills
  1168. if not exc_final.tools:
  1169. current_tool += 1
  1170. tool_name = str(current_tool)
  1171. spec = {"C": float(tool_dia)}
  1172. exc_final.tools[tool_name] = spec
  1173. else:
  1174. dia_list = []
  1175. for v in exc_final.tools.values():
  1176. dia_list.append(float(v["C"]))
  1177. if tool_dia not in dia_list:
  1178. flag_order = True
  1179. current_tool = len(dia_list) + 1
  1180. tool_name = str(current_tool)
  1181. spec = {"C": float(tool_dia)}
  1182. exc_final.tools[tool_name] = spec
  1183. else:
  1184. for k, v in exc_final.tools.items():
  1185. if v["C"] == tool_dia:
  1186. current_tool = int(k)
  1187. break
  1188. # rebuild the slots list of dict's that belong to the exc_final object
  1189. for point in custom_dict_slots[tool_dia]:
  1190. exc_final.slots.append(
  1191. {
  1192. "start": point[0],
  1193. "stop": point[1],
  1194. "tool": str(current_tool)
  1195. }
  1196. )
  1197. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  1198. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  1199. current_tool = 0
  1200. if flag_order is True:
  1201. dia_list = []
  1202. temp_drills = []
  1203. temp_slots = []
  1204. temp_tools = {}
  1205. for v in exc_final.tools.values():
  1206. dia_list.append(float(v["C"]))
  1207. dia_list.sort()
  1208. for ordered_dia in dia_list:
  1209. current_tool += 1
  1210. tool_name_temp = str(current_tool)
  1211. spec_temp = {"C": float(ordered_dia)}
  1212. temp_tools[tool_name_temp] = spec_temp
  1213. for drill in exc_final.drills:
  1214. exc_tool_dia = float('%.3f' % exc_final.tools[drill['tool']]['C'])
  1215. if exc_tool_dia == ordered_dia:
  1216. temp_drills.append(
  1217. {
  1218. "point": drill["point"],
  1219. "tool": str(current_tool)
  1220. }
  1221. )
  1222. for slot in exc_final.slots:
  1223. slot_tool_dia = float('%.3f' % exc_final.tools[slot['tool']]['C'])
  1224. if slot_tool_dia == ordered_dia:
  1225. temp_slots.append(
  1226. {
  1227. "start": slot["start"],
  1228. "stop": slot["stop"],
  1229. "tool": str(current_tool)
  1230. }
  1231. )
  1232. # delete the exc_final tools, drills and slots
  1233. exc_final.tools = dict()
  1234. exc_final.drills[:] = []
  1235. exc_final.slots[:] = []
  1236. # update the exc_final tools, drills and slots with the ordered values
  1237. exc_final.tools = temp_tools
  1238. exc_final.drills[:] = temp_drills
  1239. exc_final.slots[:] = temp_slots
  1240. # create the geometry for the exc_final object
  1241. exc_final.create_geometry()
  1242. def build_ui(self):
  1243. FlatCAMObj.build_ui(self)
  1244. try:
  1245. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1246. self.ui.tools_table.itemChanged.disconnect()
  1247. except:
  1248. pass
  1249. n = len(self.tools)
  1250. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1251. self.ui.tools_table.setRowCount(n + 2)
  1252. self.tot_drill_cnt = 0
  1253. self.tot_slot_cnt = 0
  1254. self.tool_row = 0
  1255. sort = []
  1256. for k, v in list(self.tools.items()):
  1257. sort.append((k, v.get('C')))
  1258. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1259. tools = [i[0] for i in sorted_tools]
  1260. for tool_no in tools:
  1261. drill_cnt = 0 # variable to store the nr of drills per tool
  1262. slot_cnt = 0 # variable to store the nr of slots per tool
  1263. # Find no of drills for the current tool
  1264. for drill in self.drills:
  1265. if drill['tool'] == tool_no:
  1266. drill_cnt += 1
  1267. self.tot_drill_cnt += drill_cnt
  1268. # Find no of slots for the current tool
  1269. for slot in self.slots:
  1270. if slot['tool'] == tool_no:
  1271. slot_cnt += 1
  1272. self.tot_slot_cnt += slot_cnt
  1273. id = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  1274. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1275. self.ui.tools_table.setItem(self.tool_row, 0, id) # Tool name/id
  1276. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1277. # There are no drill bits in MM with more than 3 decimals diameter
  1278. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1279. if self.units == 'MM':
  1280. dia = QtWidgets.QTableWidgetItem('%.2f' % (self.tools[tool_no]['C']))
  1281. else:
  1282. dia = QtWidgets.QTableWidgetItem('%.3f' % (self.tools[tool_no]['C']))
  1283. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1284. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1285. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1286. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1287. if slot_cnt > 0:
  1288. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1289. else:
  1290. slot_count = QtWidgets.QTableWidgetItem('')
  1291. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1292. try:
  1293. if self.units == 'MM':
  1294. t_offset = self.tool_offset[float('%.2f' % float(self.tools[tool_no]['C']))]
  1295. else:
  1296. t_offset = self.tool_offset[float('%.3f' % float(self.tools[tool_no]['C']))]
  1297. except KeyError:
  1298. t_offset = self.app.defaults['excellon_offset']
  1299. tool_offset_item = QtWidgets.QTableWidgetItem('%s' % str(t_offset))
  1300. plot_item = FCCheckBox()
  1301. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  1302. if self.ui.plot_cb.isChecked():
  1303. plot_item.setChecked(True)
  1304. self.ui.tools_table.setItem(self.tool_row, 1, dia) # Diameter
  1305. self.ui.tools_table.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1306. self.ui.tools_table.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1307. self.ui.tools_table.setItem(self.tool_row, 4, tool_offset_item) # Tool offset
  1308. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  1309. self.tool_row += 1
  1310. # add a last row with the Total number of drills
  1311. empty = QtWidgets.QTableWidgetItem('')
  1312. empty.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1313. empty_1 = QtWidgets.QTableWidgetItem('')
  1314. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1315. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1316. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1317. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1318. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1319. self.ui.tools_table.setItem(self.tool_row, 0, empty)
  1320. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  1321. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1322. self.ui.tools_table.setItem(self.tool_row, 3, empty_1) # Total number of drills
  1323. font = QtGui.QFont()
  1324. font.setBold(True)
  1325. font.setWeight(75)
  1326. for k in [1, 2]:
  1327. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1328. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  1329. self.tool_row += 1
  1330. # add a last row with the Total number of slots
  1331. empty_2 = QtWidgets.QTableWidgetItem('')
  1332. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1333. empty_3 = QtWidgets.QTableWidgetItem('')
  1334. empty_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1335. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1336. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1337. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1338. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1339. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  1340. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  1341. self.ui.tools_table.setItem(self.tool_row, 2, empty_3)
  1342. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1343. for kl in [1, 2, 3]:
  1344. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  1345. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1346. # sort the tool diameter column
  1347. # self.ui.tools_table.sortItems(1)
  1348. # all the tools are selected by default
  1349. self.ui.tools_table.selectColumn(0)
  1350. #
  1351. self.ui.tools_table.resizeColumnsToContents()
  1352. self.ui.tools_table.resizeRowsToContents()
  1353. vertical_header = self.ui.tools_table.verticalHeader()
  1354. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1355. vertical_header.hide()
  1356. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1357. horizontal_header = self.ui.tools_table.horizontalHeader()
  1358. horizontal_header.setMinimumSectionSize(10)
  1359. horizontal_header.setDefaultSectionSize(70)
  1360. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1361. horizontal_header.resizeSection(0, 20)
  1362. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1363. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1364. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1365. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
  1366. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  1367. horizontal_header.resizeSection(5, 17)
  1368. self.ui.tools_table.setColumnWidth(5, 17)
  1369. # horizontal_header.setStretchLastSection(True)
  1370. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  1371. # horizontal_header.setStretchLastSection(True)
  1372. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1373. self.ui.tools_table.setSortingEnabled(False)
  1374. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  1375. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  1376. if not self.drills:
  1377. self.ui.tdlabel.hide()
  1378. self.ui.tooldia_entry.hide()
  1379. self.ui.generate_milling_button.hide()
  1380. else:
  1381. self.ui.tdlabel.show()
  1382. self.ui.tooldia_entry.show()
  1383. self.ui.generate_milling_button.show()
  1384. if not self.slots:
  1385. self.ui.stdlabel.hide()
  1386. self.ui.slot_tooldia_entry.hide()
  1387. self.ui.generate_milling_slots_button.hide()
  1388. else:
  1389. self.ui.stdlabel.show()
  1390. self.ui.slot_tooldia_entry.show()
  1391. self.ui.generate_milling_slots_button.show()
  1392. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1393. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1394. self.ui_connect()
  1395. def set_ui(self, ui):
  1396. """
  1397. Configures the user interface for this object.
  1398. Connects options to form fields.
  1399. :param ui: User interface object.
  1400. :type ui: ExcellonObjectUI
  1401. :return: None
  1402. """
  1403. FlatCAMObj.set_ui(self, ui)
  1404. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  1405. self.form_fields.update({
  1406. "plot": self.ui.plot_cb,
  1407. "solid": self.ui.solid_cb,
  1408. "drillz": self.ui.cutz_entry,
  1409. "travelz": self.ui.travelz_entry,
  1410. "feedrate": self.ui.feedrate_entry,
  1411. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  1412. "tooldia": self.ui.tooldia_entry,
  1413. "slot_tooldia": self.ui.slot_tooldia_entry,
  1414. "toolchange": self.ui.toolchange_cb,
  1415. "toolchangez": self.ui.toolchangez_entry,
  1416. "spindlespeed": self.ui.spindlespeed_entry,
  1417. "dwell": self.ui.dwell_cb,
  1418. "dwelltime": self.ui.dwelltime_entry,
  1419. "startz": self.ui.estartz_entry,
  1420. "endz": self.ui.eendz_entry,
  1421. "ppname_e": self.ui.pp_excellon_name_cb,
  1422. "z_pdepth": self.ui.pdepth_entry,
  1423. "feedrate_probe": self.ui.feedrate_probe_entry,
  1424. "gcode_type": self.ui.excellon_gcode_type_radio
  1425. })
  1426. for name in list(self.app.postprocessors.keys()):
  1427. # the HPGL postprocessor is only for Geometry not for Excellon job therefore don't add it
  1428. if name == 'hpgl':
  1429. continue
  1430. self.ui.pp_excellon_name_cb.addItem(name)
  1431. # Fill form fields
  1432. self.to_form()
  1433. # initialize the dict that holds the tools offset
  1434. t_default_offset = self.app.defaults["excellon_offset"]
  1435. if not self.tool_offset:
  1436. for value in self.tools.values():
  1437. if self.units == 'MM':
  1438. dia = float('%.2f' % float(value['C']))
  1439. else:
  1440. dia = float('%.3f' % float(value['C']))
  1441. self.tool_offset[dia] = t_default_offset
  1442. # Show/Hide Advanced Options
  1443. if self.app.defaults["global_app_level"] == 'b':
  1444. self.ui.level.setText(_(
  1445. '<span style="color:green;"><b>Basic</b></span>'
  1446. ))
  1447. self.ui.tools_table.setColumnHidden(4, True)
  1448. self.ui.estartz_label.hide()
  1449. self.ui.estartz_entry.hide()
  1450. self.ui.eendz_label.hide()
  1451. self.ui.eendz_entry.hide()
  1452. self.ui.feedrate_rapid_label.hide()
  1453. self.ui.feedrate_rapid_entry.hide()
  1454. self.ui.pdepth_label.hide()
  1455. self.ui.pdepth_entry.hide()
  1456. self.ui.feedrate_probe_label.hide()
  1457. self.ui.feedrate_probe_entry.hide()
  1458. else:
  1459. self.ui.level.setText(_(
  1460. '<span style="color:red;"><b>Advanced</b></span>'
  1461. ))
  1462. assert isinstance(self.ui, ExcellonObjectUI), \
  1463. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  1464. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1465. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  1466. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  1467. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  1468. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  1469. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  1470. def ui_connect(self):
  1471. for row in range(self.ui.tools_table.rowCount() - 2):
  1472. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  1473. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1474. def ui_disconnect(self):
  1475. for row in range(self.ui.tools_table.rowCount()):
  1476. try:
  1477. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  1478. except:
  1479. pass
  1480. try:
  1481. self.ui.plot_cb.stateChanged.disconnect()
  1482. except:
  1483. pass
  1484. def on_tool_offset_edit(self):
  1485. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1486. self.ui.tools_table.itemChanged.disconnect()
  1487. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1488. self.is_modified = True
  1489. row_of_item_changed = self.ui.tools_table.currentRow()
  1490. if self.units == 'MM':
  1491. dia = float('%.2f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1492. else:
  1493. dia = float('%.3f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1494. current_table_offset_edited = None
  1495. if self.ui.tools_table.currentItem() is not None:
  1496. try:
  1497. current_table_offset_edited = float(self.ui.tools_table.currentItem().text())
  1498. except ValueError:
  1499. # try to convert comma to decimal point. if it's still not working error message and return
  1500. try:
  1501. current_table_offset_edited = float(self.ui.tools_table.currentItem().text().replace(',', '.'))
  1502. self.ui.tools_table.currentItem().setText(
  1503. self.ui.tools_table.currentItem().text().replace(',', '.'))
  1504. except ValueError:
  1505. self.app.inform.emit(_(
  1506. "[ERROR_NOTCL] Wrong value format entered, use a number."
  1507. ))
  1508. self.ui.tools_table.currentItem().setText(str(self.tool_offset[dia]))
  1509. return
  1510. self.tool_offset[dia] = current_table_offset_edited
  1511. # we reactivate the signals after the after the tool editing
  1512. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1513. def get_selected_tools_list(self):
  1514. """
  1515. Returns the keys to the self.tools dictionary corresponding
  1516. to the selections on the tool list in the GUI.
  1517. :return: List of tools.
  1518. :rtype: list
  1519. """
  1520. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  1521. def get_selected_tools_table_items(self):
  1522. """
  1523. Returns a list of lists, each list in the list is made out of row elements
  1524. :return: List of table_tools items.
  1525. :rtype: list
  1526. """
  1527. table_tools_items = []
  1528. for x in self.ui.tools_table.selectedItems():
  1529. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  1530. # which does not have text
  1531. table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  1532. for column in range(0, self.ui.tools_table.columnCount() - 1)])
  1533. for item in table_tools_items:
  1534. item[0] = str(item[0])
  1535. return table_tools_items
  1536. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1):
  1537. """
  1538. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1539. :return: has_slots and Excellon_code
  1540. """
  1541. excellon_code = ''
  1542. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1543. has_slots = 0
  1544. # drills processing
  1545. try:
  1546. if self.drills:
  1547. length = whole + fract
  1548. for tool in self.tools:
  1549. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  1550. for drill in self.drills:
  1551. if form == 'dec' and tool == drill['tool']:
  1552. drill_x = drill['point'].x * factor
  1553. drill_y = drill['point'].y * factor
  1554. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  1555. elif e_zeros == 'LZ' and tool == drill['tool']:
  1556. drill_x = drill['point'].x * factor
  1557. drill_y = drill['point'].y * factor
  1558. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  1559. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  1560. # extract whole part and decimal part
  1561. exc_x_formatted = exc_x_formatted.partition('.')
  1562. exc_y_formatted = exc_y_formatted.partition('.')
  1563. # left padd the 'whole' part with zeros
  1564. x_whole = exc_x_formatted[0].rjust(whole, '0')
  1565. y_whole = exc_y_formatted[0].rjust(whole, '0')
  1566. # restore the coordinate padded in the left with 0 and added the decimal part
  1567. # without the decinal dot
  1568. exc_x_formatted = x_whole + exc_x_formatted[2]
  1569. exc_y_formatted = y_whole + exc_y_formatted[2]
  1570. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1571. yform=exc_y_formatted)
  1572. elif tool == drill['tool']:
  1573. drill_x = drill['point'].x * factor
  1574. drill_y = drill['point'].y * factor
  1575. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  1576. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  1577. # pad with rear zeros
  1578. exc_x_formatted.ljust(length, '0')
  1579. exc_y_formatted.ljust(length, '0')
  1580. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1581. yform=exc_y_formatted)
  1582. except Exception as e:
  1583. log.debug(str(e))
  1584. # slots processing
  1585. try:
  1586. if self.slots:
  1587. has_slots = 1
  1588. for tool in self.tools:
  1589. if int(tool) < 10:
  1590. excellon_code += 'T0' + str(tool) + '\n'
  1591. else:
  1592. excellon_code += 'T' + str(tool) + '\n'
  1593. for slot in self.slots:
  1594. if form == 'dec' and tool == slot['tool']:
  1595. start_slot_x = slot['start'].x * factor
  1596. start_slot_y = slot['start'].y * factor
  1597. stop_slot_x = slot['stop'].x * factor
  1598. stop_slot_y = slot['stop'].y * factor
  1599. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  1600. start_slot_y,
  1601. dec=fract)
  1602. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  1603. stop_slot_y,
  1604. dec=fract)
  1605. elif e_zeros == 'LZ' and tool == slot['tool']:
  1606. start_slot_x = slot['start'].x * factor
  1607. start_slot_y = slot['start'].y * factor
  1608. stop_slot_x = slot['stop'].x * factor
  1609. stop_slot_y = slot['stop'].y * factor
  1610. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1611. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1612. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1613. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1614. # extract whole part and decimal part
  1615. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  1616. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  1617. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  1618. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  1619. # left padd the 'whole' part with zeros
  1620. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  1621. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  1622. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  1623. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  1624. # restore the coordinate padded in the left with 0 and added the decimal part
  1625. # without the decinal dot
  1626. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  1627. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  1628. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  1629. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  1630. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1631. ystart=start_slot_y_formatted)
  1632. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1633. ystop=stop_slot_y_formatted)
  1634. elif tool == slot['tool']:
  1635. start_slot_x = slot['start'].x * factor
  1636. start_slot_y = slot['start'].y * factor
  1637. stop_slot_x = slot['stop'].x * factor
  1638. stop_slot_y = slot['stop'].y * factor
  1639. length = whole + fract
  1640. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1641. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1642. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1643. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1644. # pad with rear zeros
  1645. start_slot_x_formatted.ljust(length, '0')
  1646. start_slot_y_formatted.ljust(length, '0')
  1647. stop_slot_x_formatted.ljust(length, '0')
  1648. stop_slot_y_formatted.ljust(length, '0')
  1649. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1650. ystart=start_slot_y_formatted)
  1651. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1652. ystop=stop_slot_y_formatted)
  1653. except Exception as e:
  1654. log.debug(str(e))
  1655. if not self.drills and not self.slots:
  1656. log.debug("FlatCAMObj.FlatCAMExcellon.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  1657. return 'fail'
  1658. return has_slots, excellon_code
  1659. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1660. """
  1661. Note: This method is a good template for generic operations as
  1662. it takes it's options from parameters or otherwise from the
  1663. object's options and returns a (success, msg) tuple as feedback
  1664. for shell operations.
  1665. :return: Success/failure condition tuple (bool, str).
  1666. :rtype: tuple
  1667. """
  1668. # Get the tools from the list. These are keys
  1669. # to self.tools
  1670. if tools is None:
  1671. tools = self.get_selected_tools_list()
  1672. if outname is None:
  1673. outname = self.options["name"] + "_mill"
  1674. if tooldia is None:
  1675. tooldia = float(self.options["tooldia"])
  1676. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1677. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1678. sort = []
  1679. for k, v in self.tools.items():
  1680. sort.append((k, v.get('C')))
  1681. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1682. if tools == "all":
  1683. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1684. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1685. if len(tools) == 0:
  1686. self.app.inform.emit(_(
  1687. "[ERROR_NOTCL] Please select one or more tools from the list and try again."
  1688. ))
  1689. return False, "Error: No tools."
  1690. for tool in tools:
  1691. if tooldia > self.tools[tool]["C"]:
  1692. self.app.inform.emit(_(
  1693. "[ERROR_NOTCL] Milling tool for DRILLS is larger than hole size. Cancelled."
  1694. ))
  1695. return False, "Error: Milling tool is larger than hole."
  1696. def geo_init(geo_obj, app_obj):
  1697. assert isinstance(geo_obj, FlatCAMGeometry), \
  1698. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1699. app_obj.progress.emit(20)
  1700. ### Add properties to the object
  1701. # get the tool_table items in a list of row items
  1702. tool_table_items = self.get_selected_tools_table_items()
  1703. # insert an information only element in the front
  1704. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1705. geo_obj.options['Tools_in_use'] = tool_table_items
  1706. geo_obj.options['type'] = 'Excellon Geometry'
  1707. geo_obj.solid_geometry = []
  1708. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1709. # for FlatCAM is 6 decimals,
  1710. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1711. for hole in self.drills:
  1712. if hole['tool'] in tools:
  1713. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  1714. if buffer_value == 0:
  1715. geo_obj.solid_geometry.append(
  1716. Point(hole['point']).buffer(0.0000001).exterior)
  1717. else:
  1718. geo_obj.solid_geometry.append(
  1719. Point(hole['point']).buffer(buffer_value).exterior)
  1720. if use_thread:
  1721. def geo_thread(app_obj):
  1722. app_obj.new_object("geometry", outname, geo_init)
  1723. app_obj.progress.emit(100)
  1724. # Create a promise with the new name
  1725. self.app.collection.promise(outname)
  1726. # Send to worker
  1727. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1728. else:
  1729. self.app.new_object("geometry", outname, geo_init)
  1730. return True, ""
  1731. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1732. """
  1733. Note: This method is a good template for generic operations as
  1734. it takes it's options from parameters or otherwise from the
  1735. object's options and returns a (success, msg) tuple as feedback
  1736. for shell operations.
  1737. :return: Success/failure condition tuple (bool, str).
  1738. :rtype: tuple
  1739. """
  1740. # Get the tools from the list. These are keys
  1741. # to self.tools
  1742. if tools is None:
  1743. tools = self.get_selected_tools_list()
  1744. if outname is None:
  1745. outname = self.options["name"] + "_mill"
  1746. if tooldia is None:
  1747. tooldia = float(self.options["slot_tooldia"])
  1748. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1749. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1750. sort = []
  1751. for k, v in self.tools.items():
  1752. sort.append((k, v.get('C')))
  1753. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1754. if tools == "all":
  1755. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1756. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1757. if len(tools) == 0:
  1758. self.app.inform.emit(_(
  1759. "[ERROR_NOTCL] Please select one or more tools from the list and try again."
  1760. ))
  1761. return False, "Error: No tools."
  1762. for tool in tools:
  1763. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1764. adj_toolstable_tooldia = float('%.4f' % float(tooldia))
  1765. adj_file_tooldia = float('%.4f' % float(self.tools[tool]["C"]))
  1766. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  1767. self.app.inform.emit(_(
  1768. "[ERROR_NOTCL] Milling tool for SLOTS is larger than hole size. Cancelled."
  1769. ))
  1770. return False, "Error: Milling tool is larger than hole."
  1771. def geo_init(geo_obj, app_obj):
  1772. assert isinstance(geo_obj, FlatCAMGeometry), \
  1773. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1774. app_obj.progress.emit(20)
  1775. ### Add properties to the object
  1776. # get the tool_table items in a list of row items
  1777. tool_table_items = self.get_selected_tools_table_items()
  1778. # insert an information only element in the front
  1779. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1780. geo_obj.options['Tools_in_use'] = tool_table_items
  1781. geo_obj.options['type'] = 'Excellon Geometry'
  1782. geo_obj.solid_geometry = []
  1783. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1784. # for FlatCAM is 6 decimals,
  1785. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1786. for slot in self.slots:
  1787. if slot['tool'] in tools:
  1788. toolstable_tool = float('%.4f' % float(tooldia))
  1789. file_tool = float('%.4f' % float(self.tools[tool]["C"]))
  1790. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1791. # for the file_tool (tooldia actually)
  1792. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  1793. if buffer_value == 0:
  1794. start = slot['start']
  1795. stop = slot['stop']
  1796. lines_string = LineString([start, stop])
  1797. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  1798. geo_obj.solid_geometry.append(poly)
  1799. else:
  1800. start = slot['start']
  1801. stop = slot['stop']
  1802. lines_string = LineString([start, stop])
  1803. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  1804. geo_obj.solid_geometry.append(poly)
  1805. if use_thread:
  1806. def geo_thread(app_obj):
  1807. app_obj.new_object("geometry", outname + '_slot', geo_init)
  1808. app_obj.progress.emit(100)
  1809. # Create a promise with the new name
  1810. self.app.collection.promise(outname)
  1811. # Send to worker
  1812. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1813. else:
  1814. self.app.new_object("geometry", outname + '_slot', geo_init)
  1815. return True, ""
  1816. def on_generate_milling_button_click(self, *args):
  1817. self.app.report_usage("excellon_on_create_milling_drills button")
  1818. self.read_form()
  1819. self.generate_milling_drills(use_thread=False)
  1820. def on_generate_milling_slots_button_click(self, *args):
  1821. self.app.report_usage("excellon_on_create_milling_slots_button")
  1822. self.read_form()
  1823. self.generate_milling_slots(use_thread=False)
  1824. def on_pp_changed(self):
  1825. current_pp = self.ui.pp_excellon_name_cb.get_value()
  1826. if "toolchange_probe" in current_pp.lower():
  1827. self.ui.pdepth_entry.setVisible(True)
  1828. self.ui.pdepth_label.show()
  1829. self.ui.feedrate_probe_entry.setVisible(True)
  1830. self.ui.feedrate_probe_label.show()
  1831. else:
  1832. self.ui.pdepth_entry.setVisible(False)
  1833. self.ui.pdepth_label.hide()
  1834. self.ui.feedrate_probe_entry.setVisible(False)
  1835. self.ui.feedrate_probe_label.hide()
  1836. def on_create_cncjob_button_click(self, *args):
  1837. self.app.report_usage("excellon_on_create_cncjob_button")
  1838. self.read_form()
  1839. # Get the tools from the list
  1840. tools = self.get_selected_tools_list()
  1841. if len(tools) == 0:
  1842. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  1843. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  1844. # in this case regardless of the selection status of that tool, use it.
  1845. if self.ui.tools_table.rowCount() == 3:
  1846. tools.append(self.ui.tools_table.item(0, 0).text())
  1847. else:
  1848. self.app.inform.emit(_(
  1849. "[ERROR_NOTCL] Please select one or more tools from the list and try again."
  1850. ))
  1851. return
  1852. xmin = self.options['xmin']
  1853. ymin = self.options['ymin']
  1854. xmax = self.options['xmax']
  1855. ymax = self.options['ymax']
  1856. job_name = self.options["name"] + "_cnc"
  1857. pp_excellon_name = self.options["ppname_e"]
  1858. # Object initialization function for app.new_object()
  1859. def job_init(job_obj, app_obj):
  1860. assert isinstance(job_obj, FlatCAMCNCjob), \
  1861. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1862. # get the tool_table items in a list of row items
  1863. tool_table_items = self.get_selected_tools_table_items()
  1864. # insert an information only element in the front
  1865. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1866. ### Add properties to the object
  1867. job_obj.origin_kind = 'excellon'
  1868. job_obj.options['Tools_in_use'] = tool_table_items
  1869. job_obj.options['type'] = 'Excellon'
  1870. job_obj.options['ppname_e'] = pp_excellon_name
  1871. app_obj.progress.emit(20)
  1872. job_obj.z_cut = float(self.options["drillz"])
  1873. job_obj.tool_offset = self.tool_offset
  1874. job_obj.z_move = float(self.options["travelz"])
  1875. job_obj.feedrate = float(self.options["feedrate"])
  1876. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  1877. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] else None
  1878. job_obj.dwell = self.options["dwell"]
  1879. job_obj.dwelltime = float(self.options["dwelltime"])
  1880. job_obj.pp_excellon_name = pp_excellon_name
  1881. job_obj.toolchange_xy_type = "excellon"
  1882. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1883. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1884. job_obj.options['xmin'] = xmin
  1885. job_obj.options['ymin'] = ymin
  1886. job_obj.options['xmax'] = xmax
  1887. job_obj.options['ymax'] = ymax
  1888. try:
  1889. job_obj.z_pdepth = float(self.options["z_pdepth"])
  1890. except ValueError:
  1891. # try to convert comma to decimal point. if it's still not working error message and return
  1892. try:
  1893. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  1894. except ValueError:
  1895. self.app.inform.emit(
  1896. _(
  1897. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  1898. ))
  1899. try:
  1900. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  1901. except ValueError:
  1902. # try to convert comma to decimal point. if it's still not working error message and return
  1903. try:
  1904. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  1905. except ValueError:
  1906. self.app.inform.emit(
  1907. _(
  1908. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  1909. 'or self.options["feedrate_probe"]'
  1910. )
  1911. )
  1912. # There could be more than one drill size...
  1913. # job_obj.tooldia = # TODO: duplicate variable!
  1914. # job_obj.options["tooldia"] =
  1915. tools_csv = ','.join(tools)
  1916. ret_val = job_obj.generate_from_excellon_by_tool(self, tools_csv,
  1917. drillz=float(self.options['drillz']),
  1918. toolchange=self.options["toolchange"],
  1919. toolchangexy=self.app.defaults["excellon_toolchangexy"],
  1920. toolchangez=float(self.options["toolchangez"]),
  1921. startz=float(self.options["startz"]) if
  1922. self.options["startz"] else None,
  1923. endz=float(self.options["endz"]),
  1924. excellon_optimization_type=self.app.defaults[
  1925. "excellon_optimization_type"])
  1926. if ret_val == 'fail':
  1927. return 'fail'
  1928. app_obj.progress.emit(50)
  1929. job_obj.gcode_parse()
  1930. app_obj.progress.emit(60)
  1931. job_obj.create_geometry()
  1932. app_obj.progress.emit(80)
  1933. # To be run in separate thread
  1934. def job_thread(app_obj):
  1935. with self.app.proc_container.new(_("Generating CNC Code")):
  1936. app_obj.new_object("cncjob", job_name, job_init)
  1937. app_obj.progress.emit(100)
  1938. # Create promise for the new name.
  1939. self.app.collection.promise(job_name)
  1940. # Send to worker
  1941. # self.app.worker.add_task(job_thread, [self.app])
  1942. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1943. def convert_units(self, units):
  1944. factor = Excellon.convert_units(self, units)
  1945. self.options['drillz'] = float(self.options['drillz']) * factor
  1946. self.options['travelz'] = float(self.options['travelz']) * factor
  1947. self.options['feedrate'] = float(self.options['feedrate']) * factor
  1948. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  1949. self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  1950. if self.app.defaults["excellon_toolchangexy"] == '':
  1951. self.options['toolchangexy'] = "0.0, 0.0"
  1952. else:
  1953. coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  1954. if len(coords_xy) < 2:
  1955. self.app.inform.emit(_(
  1956. "[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  1957. "in the format (x, y) \nbut now there is only one value, not two. "
  1958. ))
  1959. return 'fail'
  1960. coords_xy[0] *= factor
  1961. coords_xy[1] *= factor
  1962. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1963. if self.options['startz'] is not None:
  1964. self.options['startz'] = float(self.options['startz']) * factor
  1965. self.options['endz'] = float(self.options['endz']) * factor
  1966. def on_solid_cb_click(self, *args):
  1967. if self.muted_ui:
  1968. return
  1969. self.read_form_item('solid')
  1970. self.plot()
  1971. def on_plot_cb_click(self, *args):
  1972. if self.muted_ui:
  1973. return
  1974. self.plot()
  1975. self.read_form_item('plot')
  1976. self.ui_disconnect()
  1977. cb_flag = self.ui.plot_cb.isChecked()
  1978. for row in range(self.ui.tools_table.rowCount() - 2):
  1979. table_cb = self.ui.tools_table.cellWidget(row, 5)
  1980. if cb_flag:
  1981. table_cb.setChecked(True)
  1982. else:
  1983. table_cb.setChecked(False)
  1984. self.ui_connect()
  1985. def on_plot_cb_click_table(self):
  1986. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1987. self.ui_disconnect()
  1988. # cw = self.sender()
  1989. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  1990. # cw_row = cw_index.row()
  1991. check_row = 0
  1992. self.shapes.clear(update=True)
  1993. for tool_key in self.tools:
  1994. solid_geometry = self.tools[tool_key]['solid_geometry']
  1995. # find the geo_tool_table row associated with the tool_key
  1996. for row in range(self.ui.tools_table.rowCount()):
  1997. tool_item = int(self.ui.tools_table.item(row, 0).text())
  1998. if tool_item == int(tool_key):
  1999. check_row = row
  2000. break
  2001. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  2002. self.options['plot'] = True
  2003. # self.plot_element(element=solid_geometry, visible=True)
  2004. # Plot excellon (All polygons?)
  2005. if self.options["solid"]:
  2006. for geo in solid_geometry:
  2007. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2008. visible=self.options['plot'],
  2009. layer=2)
  2010. else:
  2011. for geo in solid_geometry:
  2012. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2013. for ints in geo.interiors:
  2014. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2015. self.shapes.redraw()
  2016. # make sure that the general plot is disabled if one of the row plot's are disabled and
  2017. # if all the row plot's are enabled also enable the general plot checkbox
  2018. cb_cnt = 0
  2019. total_row = self.ui.tools_table.rowCount()
  2020. for row in range(total_row - 2):
  2021. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  2022. cb_cnt += 1
  2023. else:
  2024. cb_cnt -= 1
  2025. if cb_cnt < total_row - 2:
  2026. self.ui.plot_cb.setChecked(False)
  2027. else:
  2028. self.ui.plot_cb.setChecked(True)
  2029. self.ui_connect()
  2030. # def plot_element(self, element, color='red', visible=None, layer=None):
  2031. #
  2032. # visible = visible if visible else self.options['plot']
  2033. #
  2034. # try:
  2035. # for sub_el in element:
  2036. # self.plot_element(sub_el)
  2037. #
  2038. # except TypeError: # Element is not iterable...
  2039. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2040. def plot(self, kind=None):
  2041. # Does all the required setup and returns False
  2042. # if the 'ptint' option is set to False.
  2043. if not FlatCAMObj.plot(self):
  2044. return
  2045. try:
  2046. # Plot excellon (All polygons?)
  2047. if self.options["solid"]:
  2048. for tool in self.tools:
  2049. for geo in self.tools[tool]['solid_geometry']:
  2050. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2051. visible=self.options['plot'],
  2052. layer=2)
  2053. else:
  2054. for tool in self.tools:
  2055. for geo in self.tools[tool]['solid_geometry']:
  2056. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2057. for ints in geo.interiors:
  2058. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2059. self.shapes.redraw()
  2060. return
  2061. except (ObjectDeleted, AttributeError, KeyError):
  2062. self.shapes.clear(update=True)
  2063. # this stays for compatibility reasons, in case we try to open old projects
  2064. try:
  2065. _ = iter(self.solid_geometry)
  2066. except TypeError:
  2067. self.solid_geometry = [self.solid_geometry]
  2068. try:
  2069. # Plot excellon (All polygons?)
  2070. if self.options["solid"]:
  2071. for geo in self.solid_geometry:
  2072. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF', visible=self.options['plot'],
  2073. layer=2)
  2074. else:
  2075. for geo in self.solid_geometry:
  2076. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2077. for ints in geo.interiors:
  2078. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2079. self.shapes.redraw()
  2080. except (ObjectDeleted, AttributeError):
  2081. self.shapes.clear(update=True)
  2082. # try:
  2083. # # Plot excellon (All polygons?)
  2084. # if self.options["solid"]:
  2085. # for geo_type in self.solid_geometry:
  2086. # if geo_type is not None:
  2087. # if type(geo_type) is dict:
  2088. # for tooldia in geo_type:
  2089. # geo_list = geo_type[tooldia]
  2090. # for geo in geo_list:
  2091. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2092. # visible=self.options['plot'],
  2093. # layer=2)
  2094. # else:
  2095. # self.add_shape(shape=geo_type, color='#750000BF', face_color='#C40000BF',
  2096. # visible=self.options['plot'],
  2097. # layer=2)
  2098. # else:
  2099. # for geo_type in self.solid_geometry:
  2100. # if geo_type is not None:
  2101. # if type(geo_type) is dict:
  2102. # for tooldia in geo_type:
  2103. # geo_list = geo_type[tooldia]
  2104. # for geo in geo_list:
  2105. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2106. # for ints in geo.interiors:
  2107. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2108. # else:
  2109. # self.add_shape(shape=geo_type.exterior, color='red', visible=self.options['plot'])
  2110. # for ints in geo_type.interiors:
  2111. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2112. # self.shapes.redraw()
  2113. # except (ObjectDeleted, AttributeError):
  2114. # self.shapes.clear(update=True)
  2115. class FlatCAMGeometry(FlatCAMObj, Geometry):
  2116. """
  2117. Geometric object not associated with a specific
  2118. format.
  2119. """
  2120. optionChanged = QtCore.pyqtSignal(str)
  2121. ui_type = GeometryObjectUI
  2122. @staticmethod
  2123. def merge(geo_list, geo_final, multigeo=None):
  2124. """
  2125. Merges the geometry of objects in grb_list into
  2126. the geometry of geo_final.
  2127. :param geo_list: List of FlatCAMGerber Objects to join.
  2128. :param geo_final: Destination FlatCAMGerber object.
  2129. :return: None
  2130. """
  2131. if geo_final.solid_geometry is None:
  2132. geo_final.solid_geometry = []
  2133. if type(geo_final.solid_geometry) is not list:
  2134. geo_final.solid_geometry = [geo_final.solid_geometry]
  2135. for geo in geo_list:
  2136. for option in geo.options:
  2137. if option is not 'name':
  2138. try:
  2139. geo_final.options[option] = geo.options[option]
  2140. except:
  2141. log.warning("Failed to copy option.", option)
  2142. # Expand lists
  2143. if type(geo) is list:
  2144. FlatCAMGeometry.merge(geo, geo_final)
  2145. # If not list, just append
  2146. else:
  2147. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  2148. if multigeo is None or multigeo == False:
  2149. geo_final.multigeo = False
  2150. try:
  2151. geo_final.solid_geometry.append(geo.solid_geometry)
  2152. except Exception as e:
  2153. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  2154. else:
  2155. geo_final.multigeo = True
  2156. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  2157. # tools object attribute, as a key value
  2158. geo_final.solid_geometry = []
  2159. # find the tool_uid maximum value in the geo_final
  2160. geo_final_uid_list = []
  2161. for key in geo_final.tools:
  2162. geo_final_uid_list.append(int(key))
  2163. try:
  2164. max_uid = max(geo_final_uid_list, key=int)
  2165. except ValueError:
  2166. max_uid = 0
  2167. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  2168. # to merge the obj.tools as it is likely there is none to merge.
  2169. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  2170. for tool_uid in geo.tools:
  2171. max_uid += 1
  2172. geo_final.tools[max_uid] = deepcopy(geo.tools[tool_uid])
  2173. @staticmethod
  2174. def get_pts(o):
  2175. """
  2176. Returns a list of all points in the object, where
  2177. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  2178. of such. Search is done recursively.
  2179. :param: geometric object
  2180. :return: List of points
  2181. :rtype: list
  2182. """
  2183. pts = []
  2184. ## Iterable: descend into each item.
  2185. try:
  2186. for subo in o:
  2187. pts += FlatCAMGeometry.get_pts(subo)
  2188. ## Non-iterable
  2189. except TypeError:
  2190. if o is not None:
  2191. if type(o) == MultiPolygon:
  2192. for poly in o:
  2193. pts += FlatCAMGeometry.get_pts(poly)
  2194. ## Descend into .exerior and .interiors
  2195. elif type(o) == Polygon:
  2196. pts += FlatCAMGeometry.get_pts(o.exterior)
  2197. for i in o.interiors:
  2198. pts += FlatCAMGeometry.get_pts(i)
  2199. elif type(o) == MultiLineString:
  2200. for line in o:
  2201. pts += FlatCAMGeometry.get_pts(line)
  2202. ## Has .coords: list them.
  2203. else:
  2204. pts += list(o.coords)
  2205. else:
  2206. return
  2207. return pts
  2208. def __init__(self, name):
  2209. FlatCAMObj.__init__(self, name)
  2210. Geometry.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  2211. self.kind = "geometry"
  2212. self.options.update({
  2213. "plot": True,
  2214. "cutz": -0.002,
  2215. "vtipdia": 0.1,
  2216. "vtipangle": 30,
  2217. "travelz": 0.1,
  2218. "feedrate": 5.0,
  2219. "feedrate_z": 5.0,
  2220. "feedrate_rapid": 5.0,
  2221. "spindlespeed": None,
  2222. "dwell": True,
  2223. "dwelltime": 1000,
  2224. "multidepth": False,
  2225. "depthperpass": 0.002,
  2226. "extracut": False,
  2227. "endz": 2.0,
  2228. "toolchange": False,
  2229. "toolchangez": 1.0,
  2230. "toolchangexy": "0.0, 0.0",
  2231. "startz": None,
  2232. "ppname_g": 'default',
  2233. "z_pdepth": -0.02,
  2234. "feedrate_probe": 3.0,
  2235. })
  2236. if "cnctooldia" not in self.options:
  2237. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  2238. self.options["startz"] = self.app.defaults["geometry_startz"]
  2239. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  2240. self.tooluid = 0
  2241. '''
  2242. self.tools = {}
  2243. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  2244. tool_id of the tools and the value is another dict that will hold the data under the following form:
  2245. {tooluid: {
  2246. 'tooldia': 1,
  2247. 'offset': 'Path',
  2248. 'offset_value': 0.0
  2249. 'type': 'Rough',
  2250. 'tool_type': 'C1',
  2251. 'data': self.default_tool_data
  2252. 'solid_geometry': []
  2253. }
  2254. }
  2255. '''
  2256. self.tools = {}
  2257. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  2258. # those elements are the ones used for generating GCode
  2259. self.sel_tools = {}
  2260. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  2261. self.type_item_options = [_("Iso"), _("Rough"), _("Finish")]
  2262. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  2263. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  2264. self.v_tool_type = None
  2265. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  2266. # the default value is False
  2267. self.multigeo = False
  2268. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  2269. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  2270. self. special_group = None
  2271. # Attributes to be included in serialization
  2272. # Always append to it because it carries contents
  2273. # from predecessors.
  2274. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  2275. def build_ui(self):
  2276. self.ui_disconnect()
  2277. FlatCAMObj.build_ui(self)
  2278. offset = 0
  2279. tool_idx = 0
  2280. n = len(self.tools)
  2281. self.ui.geo_tools_table.setRowCount(n)
  2282. for tooluid_key, tooluid_value in self.tools.items():
  2283. tool_idx += 1
  2284. row_no = tool_idx - 1
  2285. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  2286. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2287. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  2288. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  2289. # There are no tool bits in MM with more than 3 decimals diameter.
  2290. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  2291. if self.units == 'MM':
  2292. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  2293. else:
  2294. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  2295. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2296. offset_item = QtWidgets.QComboBox()
  2297. for item in self.offset_item_options:
  2298. offset_item.addItem(item)
  2299. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  2300. idx = offset_item.findText(tooluid_value['offset'])
  2301. offset_item.setCurrentIndex(idx)
  2302. type_item = QtWidgets.QComboBox()
  2303. for item in self.type_item_options:
  2304. type_item.addItem(item)
  2305. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2306. idx = type_item.findText(tooluid_value['type'])
  2307. type_item.setCurrentIndex(idx)
  2308. tool_type_item = QtWidgets.QComboBox()
  2309. for item in self.tool_type_item_options:
  2310. tool_type_item.addItem(item)
  2311. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2312. idx = tool_type_item.findText(tooluid_value['tool_type'])
  2313. tool_type_item.setCurrentIndex(idx)
  2314. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  2315. plot_item = FCCheckBox()
  2316. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2317. if self.ui.plot_cb.isChecked():
  2318. plot_item.setChecked(True)
  2319. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  2320. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  2321. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  2322. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  2323. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  2324. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  2325. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  2326. try:
  2327. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  2328. except:
  2329. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  2330. # make the diameter column editable
  2331. for row in range(tool_idx):
  2332. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  2333. QtCore.Qt.ItemIsEditable |
  2334. QtCore.Qt.ItemIsEnabled)
  2335. # sort the tool diameter column
  2336. # self.ui.geo_tools_table.sortItems(1)
  2337. # all the tools are selected by default
  2338. # self.ui.geo_tools_table.selectColumn(0)
  2339. self.ui.geo_tools_table.resizeColumnsToContents()
  2340. self.ui.geo_tools_table.resizeRowsToContents()
  2341. vertical_header = self.ui.geo_tools_table.verticalHeader()
  2342. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2343. vertical_header.hide()
  2344. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2345. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  2346. horizontal_header.setMinimumSectionSize(10)
  2347. horizontal_header.setDefaultSectionSize(70)
  2348. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2349. horizontal_header.resizeSection(0, 20)
  2350. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2351. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2352. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2353. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  2354. horizontal_header.resizeSection(4, 40)
  2355. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  2356. horizontal_header.resizeSection(4, 17)
  2357. # horizontal_header.setStretchLastSection(True)
  2358. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2359. self.ui.geo_tools_table.setColumnWidth(0, 20)
  2360. self.ui.geo_tools_table.setColumnWidth(4, 40)
  2361. self.ui.geo_tools_table.setColumnWidth(6, 17)
  2362. # self.ui.geo_tools_table.setSortingEnabled(True)
  2363. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  2364. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  2365. # update UI for all rows - useful after units conversion but only if there is at least one row
  2366. row_cnt = self.ui.geo_tools_table.rowCount()
  2367. if row_cnt > 0:
  2368. for r in range(row_cnt):
  2369. self.update_ui(r)
  2370. # select only the first tool / row
  2371. selected_row = 0
  2372. try:
  2373. self.select_tools_table_row(selected_row, clearsel=True)
  2374. # update the Geometry UI
  2375. self.update_ui()
  2376. except Exception as e:
  2377. # when the tools table is empty there will be this error but once the table is populated it will go away
  2378. log.debug(str(e))
  2379. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  2380. # and can create some problems
  2381. if self.multigeo is False:
  2382. self.ui.geo_tools_table.setColumnHidden(6, True)
  2383. else:
  2384. self.ui.geo_tools_table.setColumnHidden(6, False)
  2385. self.set_tool_offset_visibility(selected_row)
  2386. self.ui_connect()
  2387. def set_ui(self, ui):
  2388. FlatCAMObj.set_ui(self, ui)
  2389. log.debug("FlatCAMGeometry.set_ui()")
  2390. assert isinstance(self.ui, GeometryObjectUI), \
  2391. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  2392. # populate postprocessor names in the combobox
  2393. for name in list(self.app.postprocessors.keys()):
  2394. self.ui.pp_geometry_name_cb.addItem(name)
  2395. self.form_fields.update({
  2396. "plot": self.ui.plot_cb,
  2397. "cutz": self.ui.cutz_entry,
  2398. "vtipdia": self.ui.tipdia_entry,
  2399. "vtipangle": self.ui.tipangle_entry,
  2400. "travelz": self.ui.travelz_entry,
  2401. "feedrate": self.ui.cncfeedrate_entry,
  2402. "feedrate_z": self.ui.cncplunge_entry,
  2403. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  2404. "spindlespeed": self.ui.cncspindlespeed_entry,
  2405. "dwell": self.ui.dwell_cb,
  2406. "dwelltime": self.ui.dwelltime_entry,
  2407. "multidepth": self.ui.mpass_cb,
  2408. "ppname_g": self.ui.pp_geometry_name_cb,
  2409. "z_pdepth": self.ui.pdepth_entry,
  2410. "feedrate_probe": self.ui.feedrate_probe_entry,
  2411. "depthperpass": self.ui.maxdepth_entry,
  2412. "extracut": self.ui.extracut_cb,
  2413. "toolchange": self.ui.toolchangeg_cb,
  2414. "toolchangez": self.ui.toolchangez_entry,
  2415. "endz": self.ui.gendz_entry,
  2416. })
  2417. # Fill form fields only on object create
  2418. self.to_form()
  2419. self.ui.tipdialabel.hide()
  2420. self.ui.tipdia_entry.hide()
  2421. self.ui.tipanglelabel.hide()
  2422. self.ui.tipangle_entry.hide()
  2423. self.ui.cutz_entry.setDisabled(False)
  2424. # store here the default data for Geometry Data
  2425. self.default_data = {}
  2426. self.default_data.update({
  2427. "name": None,
  2428. "plot": None,
  2429. "cutz": None,
  2430. "vtipdia": None,
  2431. "vtipangle": None,
  2432. "travelz": None,
  2433. "feedrate": None,
  2434. "feedrate_z": None,
  2435. "feedrate_rapid": None,
  2436. "dwell": None,
  2437. "dwelltime": None,
  2438. "multidepth": None,
  2439. "ppname_g": None,
  2440. "depthperpass": None,
  2441. "extracut": None,
  2442. "toolchange": None,
  2443. "toolchangez": None,
  2444. "endz": None,
  2445. "spindlespeed": None,
  2446. "toolchangexy": None,
  2447. "startz": None
  2448. })
  2449. # fill in self.default_data values from self.options
  2450. for def_key in self.default_data:
  2451. for opt_key, opt_val in self.options.items():
  2452. if def_key == opt_key:
  2453. self.default_data[def_key] = opt_val
  2454. self.tooluid += 1
  2455. if not self.tools:
  2456. self.tools.update({
  2457. self.tooluid: {
  2458. 'tooldia': float(self.options["cnctooldia"]),
  2459. 'offset': ('Path'),
  2460. 'offset_value': 0.0,
  2461. 'type': _('Rough'),
  2462. 'tool_type': 'C1',
  2463. 'data': self.default_data,
  2464. 'solid_geometry': self.solid_geometry
  2465. }
  2466. })
  2467. else:
  2468. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  2469. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  2470. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  2471. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  2472. # following convoluted way of changing the keys from string to float type
  2473. temp_tools = {}
  2474. new_key = 0.0
  2475. for tooluid_key in self.tools:
  2476. val = deepcopy(self.tools[tooluid_key])
  2477. new_key = deepcopy(int(tooluid_key))
  2478. temp_tools[new_key] = val
  2479. self.tools.clear()
  2480. self.tools = deepcopy(temp_tools)
  2481. self.ui.tool_offset_entry.hide()
  2482. self.ui.tool_offset_lbl.hide()
  2483. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  2484. self.old_pp_state = self.default_data['multidepth']
  2485. self.old_toolchangeg_state = self.default_data['toolchange']
  2486. if not isinstance(self.ui, GeometryObjectUI):
  2487. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  2488. return
  2489. self.ui.geo_tools_table.setupContextMenu()
  2490. self.ui.geo_tools_table.addContextMenu(
  2491. _("Copy"), self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  2492. self.ui.geo_tools_table.addContextMenu(
  2493. _("Delete"), lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  2494. # Show/Hide Advanced Options
  2495. if self.app.defaults["global_app_level"] == 'b':
  2496. self.ui.level.setText(_(
  2497. '<span style="color:green;"><b>Basic</b></span>'
  2498. ))
  2499. self.ui.geo_tools_table.setColumnHidden(2, True)
  2500. self.ui.geo_tools_table.setColumnHidden(3, True)
  2501. self.ui.geo_tools_table.setColumnHidden(4, True)
  2502. self.ui.addtool_entry_lbl.hide()
  2503. self.ui.addtool_entry.hide()
  2504. self.ui.addtool_btn.hide()
  2505. self.ui.copytool_btn.hide()
  2506. self.ui.deltool_btn.hide()
  2507. self.ui.endzlabel.hide()
  2508. self.ui.gendz_entry.hide()
  2509. self.ui.fr_rapidlabel.hide()
  2510. self.ui.cncfeedrate_rapid_entry.hide()
  2511. self.ui.extracut_cb.hide()
  2512. self.ui.pdepth_label.hide()
  2513. self.ui.pdepth_entry.hide()
  2514. self.ui.feedrate_probe_label.hide()
  2515. self.ui.feedrate_probe_entry.hide()
  2516. else:
  2517. self.ui.level.setText(_(
  2518. '<span style="color:red;"><b>Advanced</b></span>'
  2519. ))
  2520. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2521. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  2522. self.ui.paint_tool_button.clicked.connect(lambda: self.app.paint_tool.run(toggle=False))
  2523. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  2524. self.ui.addtool_entry.returnPressed.connect(lambda: self.on_tool_add())
  2525. def set_tool_offset_visibility(self, current_row):
  2526. if current_row is None:
  2527. return
  2528. try:
  2529. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  2530. if tool_offset is not None:
  2531. tool_offset_txt = tool_offset.currentText()
  2532. if tool_offset_txt == ('Custom'):
  2533. self.ui.tool_offset_entry.show()
  2534. self.ui.tool_offset_lbl.show()
  2535. else:
  2536. self.ui.tool_offset_entry.hide()
  2537. self.ui.tool_offset_lbl.hide()
  2538. except Exception as e:
  2539. log.debug("set_tool_offset_visibility() --> " + str(e))
  2540. return
  2541. def on_offset_value_edited(self):
  2542. '''
  2543. This will save the offset_value into self.tools storage whenever the oofset value is edited
  2544. :return:
  2545. '''
  2546. for current_row in self.ui.geo_tools_table.selectedItems():
  2547. # sometime the header get selected and it has row number -1
  2548. # we don't want to do anything with the header :)
  2549. if current_row.row() < 0:
  2550. continue
  2551. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2552. self.set_tool_offset_visibility(current_row.row())
  2553. for tooluid_key, tooluid_value in self.tools.items():
  2554. if int(tooluid_key) == tool_uid:
  2555. try:
  2556. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  2557. except ValueError:
  2558. # try to convert comma to decimal point. if it's still not working error message and return
  2559. try:
  2560. tooluid_value['offset_value'] = float(
  2561. self.ui.tool_offset_entry.get_value().replace(',', '.')
  2562. )
  2563. except ValueError:
  2564. self.app.inform.emit(_(
  2565. "[ERROR_NOTCL] Wrong value format entered, "
  2566. "use a number."
  2567. )
  2568. )
  2569. return
  2570. def ui_connect(self):
  2571. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2572. # changes in geometry UI
  2573. for i in range(self.ui.grid3.count()):
  2574. try:
  2575. # works for CheckBoxes
  2576. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  2577. except:
  2578. # works for ComboBoxes
  2579. try:
  2580. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  2581. except:
  2582. # works for Entry
  2583. try:
  2584. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  2585. except:
  2586. pass
  2587. for row in range(self.ui.geo_tools_table.rowCount()):
  2588. for col in [2, 3, 4]:
  2589. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  2590. self.on_tooltable_cellwidget_change)
  2591. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2592. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  2593. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  2594. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  2595. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  2596. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  2597. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  2598. for row in range(self.ui.geo_tools_table.rowCount()):
  2599. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  2600. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2601. def ui_disconnect(self):
  2602. try:
  2603. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2604. # changes in geometry UI
  2605. for i in range(self.ui.grid3.count()):
  2606. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  2607. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  2608. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  2609. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  2610. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  2611. isinstance(self.ui.grid3.itemAt(i).widget(), IntEntry) or \
  2612. isinstance(self.ui.grid3.itemAt(i).widget(), FCEntry):
  2613. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  2614. except:
  2615. pass
  2616. try:
  2617. for row in range(self.ui.geo_tools_table.rowCount()):
  2618. for col in [2, 3, 4]:
  2619. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2620. except:
  2621. pass
  2622. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2623. try:
  2624. self.ui.addtool_btn.clicked.disconnect()
  2625. except:
  2626. pass
  2627. try:
  2628. self.ui.copytool_btn.clicked.disconnect()
  2629. except:
  2630. pass
  2631. try:
  2632. self.ui.deltool_btn.clicked.disconnect()
  2633. except:
  2634. pass
  2635. try:
  2636. self.ui.geo_tools_table.currentItemChanged.disconnect()
  2637. except:
  2638. pass
  2639. try:
  2640. self.ui.geo_tools_table.itemChanged.disconnect()
  2641. except:
  2642. pass
  2643. try:
  2644. self.ui.tool_offset_entry.editingFinished.disconnect()
  2645. except:
  2646. pass
  2647. for row in range(self.ui.geo_tools_table.rowCount()):
  2648. try:
  2649. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  2650. except:
  2651. pass
  2652. try:
  2653. self.ui.plot_cb.stateChanged.disconnect()
  2654. except:
  2655. pass
  2656. def on_tool_add(self, dia=None):
  2657. self.ui_disconnect()
  2658. last_offset = None
  2659. last_offset_value = None
  2660. last_type = None
  2661. last_tool_type = None
  2662. last_data = None
  2663. last_solid_geometry = []
  2664. # if a Tool diameter entered is a char instead a number the final message of Tool adding is changed
  2665. # because the Default value for Tool is used.
  2666. change_message = False
  2667. if dia is not None:
  2668. tooldia = dia
  2669. else:
  2670. try:
  2671. tooldia = float(self.ui.addtool_entry.get_value())
  2672. except ValueError:
  2673. # try to convert comma to decimal point. if it's still not working error message and return
  2674. try:
  2675. tooldia = float(self.ui.addtool_entry.get_value().replace(',', '.'))
  2676. except ValueError:
  2677. change_message = True
  2678. tooldia = float(self.app.defaults["geometry_cnctooldia"])
  2679. if tooldia is None:
  2680. self.build_ui()
  2681. self.app.inform.emit(_(
  2682. "[ERROR_NOTCL] Please enter the desired tool diameter in Float format."
  2683. ))
  2684. return
  2685. # construct a list of all 'tooluid' in the self.tools
  2686. tool_uid_list = []
  2687. for tooluid_key in self.tools:
  2688. tool_uid_item = int(tooluid_key)
  2689. tool_uid_list.append(tool_uid_item)
  2690. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2691. if not tool_uid_list:
  2692. max_uid = 0
  2693. else:
  2694. max_uid = max(tool_uid_list)
  2695. self.tooluid = max_uid + 1
  2696. if self.units == 'IN':
  2697. tooldia = float('%.4f' % tooldia)
  2698. else:
  2699. tooldia = float('%.2f' % tooldia)
  2700. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  2701. # otherwise we add a tool with data copied from last tool
  2702. if not self.tools:
  2703. self.tools.update({
  2704. self.tooluid: {
  2705. 'tooldia': tooldia,
  2706. 'offset': ('Path'),
  2707. 'offset_value': 0.0,
  2708. 'type': _('Rough'),
  2709. 'tool_type': 'C1',
  2710. 'data': deepcopy(self.default_data),
  2711. 'solid_geometry': self.solid_geometry
  2712. }
  2713. })
  2714. else:
  2715. # print("LAST", self.tools[maxuid])
  2716. last_data = self.tools[max_uid]['data']
  2717. last_offset = self.tools[max_uid]['offset']
  2718. last_offset_value = self.tools[max_uid]['offset_value']
  2719. last_type = self.tools[max_uid]['type']
  2720. last_tool_type = self.tools[max_uid]['tool_type']
  2721. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  2722. # if previous geometry was empty (it may happen for the first tool added)
  2723. # then copy the object.solid_geometry
  2724. if not last_solid_geometry:
  2725. last_solid_geometry = self.solid_geometry
  2726. self.tools.update({
  2727. self.tooluid: {
  2728. 'tooldia': tooldia,
  2729. 'offset': last_offset,
  2730. 'offset_value': last_offset_value,
  2731. 'type': last_type,
  2732. 'tool_type': last_tool_type,
  2733. 'data': deepcopy(last_data),
  2734. 'solid_geometry': deepcopy(last_solid_geometry)
  2735. }
  2736. })
  2737. # print("CURRENT", self.tools[-1])
  2738. self.ui.tool_offset_entry.hide()
  2739. self.ui.tool_offset_lbl.hide()
  2740. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2741. try:
  2742. self.ser_attrs.remove('tools')
  2743. except:
  2744. pass
  2745. self.ser_attrs.append('tools')
  2746. if change_message is False:
  2747. self.app.inform.emit(_(
  2748. "[success] Tool added in Tool Table."
  2749. ))
  2750. else:
  2751. change_message = False
  2752. self.app.inform.emit(_(
  2753. "[ERROR_NOTCL] Default Tool added. Wrong value format entered."
  2754. ))
  2755. self.build_ui()
  2756. def on_tool_copy(self, all=None):
  2757. self.ui_disconnect()
  2758. # find the tool_uid maximum value in the self.tools
  2759. uid_list = []
  2760. for key in self.tools:
  2761. uid_list.append(int(key))
  2762. try:
  2763. max_uid = max(uid_list, key=int)
  2764. except ValueError:
  2765. max_uid = 0
  2766. if all is None:
  2767. if self.ui.geo_tools_table.selectedItems():
  2768. for current_row in self.ui.geo_tools_table.selectedItems():
  2769. # sometime the header get selected and it has row number -1
  2770. # we don't want to do anything with the header :)
  2771. if current_row.row() < 0:
  2772. continue
  2773. try:
  2774. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2775. self.set_tool_offset_visibility(current_row.row())
  2776. max_uid += 1
  2777. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  2778. except AttributeError:
  2779. self.app.inform.emit(_(
  2780. "[WARNING_NOTCL] Failed. Select a tool to copy."
  2781. ))
  2782. self.build_ui()
  2783. return
  2784. except Exception as e:
  2785. log.debug("on_tool_copy() --> " + str(e))
  2786. # deselect the table
  2787. # self.ui.geo_tools_table.clearSelection()
  2788. else:
  2789. self.app.inform.emit(_(
  2790. "[WARNING_NOTCL] Failed. Select a tool to copy."
  2791. ))
  2792. self.build_ui()
  2793. return
  2794. else:
  2795. # we copy all tools in geo_tools_table
  2796. try:
  2797. temp_tools = deepcopy(self.tools)
  2798. max_uid += 1
  2799. for tooluid in temp_tools:
  2800. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  2801. temp_tools.clear()
  2802. except Exception as e:
  2803. log.debug("on_tool_copy() --> " + str(e))
  2804. # if there are no more tools in geo tools table then hide the tool offset
  2805. if not self.tools:
  2806. self.ui.tool_offset_entry.hide()
  2807. self.ui.tool_offset_lbl.hide()
  2808. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2809. try:
  2810. self.ser_attrs.remove('tools')
  2811. except:
  2812. pass
  2813. self.ser_attrs.append('tools')
  2814. self.build_ui()
  2815. self.app.inform.emit(_(
  2816. "[success] Tool was copied in Tool Table."
  2817. ))
  2818. def on_tool_edit(self, current_item):
  2819. self.ui_disconnect()
  2820. current_row = current_item.row()
  2821. try:
  2822. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  2823. except ValueError:
  2824. # try to convert comma to decimal point. if it's still not working error message and return
  2825. try:
  2826. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  2827. except ValueError:
  2828. self.app.inform.emit(_(
  2829. "[ERROR_NOTCL] Wrong value format entered, "
  2830. "use a number."
  2831. ))
  2832. return
  2833. tool_dia = float('%.4f' % d)
  2834. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2835. self.tools[tooluid]['tooldia'] = tool_dia
  2836. try:
  2837. self.ser_attrs.remove('tools')
  2838. self.ser_attrs.append('tools')
  2839. except:
  2840. pass
  2841. self.app.inform.emit(_(
  2842. "[success] Tool was edited in Tool Table."
  2843. ))
  2844. self.build_ui()
  2845. def on_tool_delete(self, all=None):
  2846. self.ui_disconnect()
  2847. if all is None:
  2848. if self.ui.geo_tools_table.selectedItems():
  2849. for current_row in self.ui.geo_tools_table.selectedItems():
  2850. # sometime the header get selected and it has row number -1
  2851. # we don't want to do anything with the header :)
  2852. if current_row.row() < 0:
  2853. continue
  2854. try:
  2855. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2856. self.set_tool_offset_visibility(current_row.row())
  2857. temp_tools = deepcopy(self.tools)
  2858. for tooluid_key in self.tools:
  2859. if int(tooluid_key) == tooluid_del:
  2860. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  2861. # as a property of the object otherwise there will be nothing to hold it
  2862. if len(self.tools) == 1:
  2863. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2864. temp_tools.pop(tooluid_del, None)
  2865. self.tools = deepcopy(temp_tools)
  2866. temp_tools.clear()
  2867. except AttributeError:
  2868. self.app.inform.emit(_(
  2869. "[WARNING_NOTCL] Failed. Select a tool to delete."
  2870. ))
  2871. self.build_ui()
  2872. return
  2873. except Exception as e:
  2874. log.debug("on_tool_delete() --> " + str(e))
  2875. # deselect the table
  2876. # self.ui.geo_tools_table.clearSelection()
  2877. else:
  2878. self.app.inform.emit(_(
  2879. "[WARNING_NOTCL] Failed. Select a tool to delete."
  2880. ))
  2881. self.build_ui()
  2882. return
  2883. else:
  2884. # we delete all tools in geo_tools_table
  2885. self.tools.clear()
  2886. self.app.plot_all()
  2887. # if there are no more tools in geo tools table then hide the tool offset
  2888. if not self.tools:
  2889. self.ui.tool_offset_entry.hide()
  2890. self.ui.tool_offset_lbl.hide()
  2891. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2892. try:
  2893. self.ser_attrs.remove('tools')
  2894. except:
  2895. pass
  2896. self.ser_attrs.append('tools')
  2897. self.build_ui()
  2898. self.app.inform.emit(_(
  2899. "[success] Tool was deleted in Tool Table."
  2900. ))
  2901. obj_active = self.app.collection.get_active()
  2902. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  2903. # we make it back SingleGeo
  2904. if self.ui.geo_tools_table.rowCount() <= 0:
  2905. obj_active.multigeo = False
  2906. obj_active.options['xmin'] = 0
  2907. obj_active.options['ymin'] = 0
  2908. obj_active.options['xmax'] = 0
  2909. obj_active.options['ymax'] = 0
  2910. if obj_active.multigeo is True:
  2911. try:
  2912. xmin, ymin, xmax, ymax = obj_active.bounds()
  2913. obj_active.options['xmin'] = xmin
  2914. obj_active.options['ymin'] = ymin
  2915. obj_active.options['xmax'] = xmax
  2916. obj_active.options['ymax'] = ymax
  2917. except:
  2918. obj_active.options['xmin'] = 0
  2919. obj_active.options['ymin'] = 0
  2920. obj_active.options['xmax'] = 0
  2921. obj_active.options['ymax'] = 0
  2922. def on_row_selection_change(self):
  2923. self.update_ui()
  2924. def update_ui(self, row=None):
  2925. self.ui_disconnect()
  2926. if row is None:
  2927. try:
  2928. current_row = self.ui.geo_tools_table.currentRow()
  2929. except:
  2930. current_row = 0
  2931. else:
  2932. current_row = row
  2933. if current_row < 0:
  2934. current_row = 0
  2935. self.set_tool_offset_visibility(current_row)
  2936. # populate the form with the data from the tool associated with the row parameter
  2937. try:
  2938. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2939. except Exception as e:
  2940. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2941. return
  2942. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  2943. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  2944. try:
  2945. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  2946. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  2947. except Exception as e:
  2948. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2949. return
  2950. try:
  2951. # set the form with data from the newly selected tool
  2952. for tooluid_key, tooluid_value in self.tools.items():
  2953. if int(tooluid_key) == tooluid:
  2954. for key, value in tooluid_value.items():
  2955. if key == 'data':
  2956. form_value_storage = tooluid_value[key]
  2957. self.update_form(form_value_storage)
  2958. if key == 'offset_value':
  2959. # update the offset value in the entry even if the entry is hidden
  2960. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  2961. if key == 'tool_type' and value == 'V':
  2962. self.update_cutz()
  2963. except Exception as e:
  2964. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2965. self.ui_connect()
  2966. def ui_update_v_shape(self, tool_type_txt):
  2967. if tool_type_txt == 'V':
  2968. self.ui.tipdialabel.show()
  2969. self.ui.tipdia_entry.show()
  2970. self.ui.tipanglelabel.show()
  2971. self.ui.tipangle_entry.show()
  2972. self.ui.cutz_entry.setDisabled(True)
  2973. self.update_cutz()
  2974. else:
  2975. self.ui.tipdialabel.hide()
  2976. self.ui.tipdia_entry.hide()
  2977. self.ui.tipanglelabel.hide()
  2978. self.ui.tipangle_entry.hide()
  2979. self.ui.cutz_entry.setDisabled(False)
  2980. def update_cutz(self):
  2981. try:
  2982. vdia = float(self.ui.tipdia_entry.get_value())
  2983. except ValueError:
  2984. # try to convert comma to decimal point. if it's still not working error message and return
  2985. try:
  2986. vdia = float(self.ui.tipdia_entry.get_value().replace(',', '.'))
  2987. except ValueError:
  2988. self.app.inform.emit(_(
  2989. "[ERROR_NOTCL] Wrong value format entered, "
  2990. "use a number."
  2991. ))
  2992. return
  2993. try:
  2994. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  2995. except ValueError:
  2996. # try to convert comma to decimal point. if it's still not working error message and return
  2997. try:
  2998. half_vangle = float(self.ui.tipangle_entry.get_value().replace(',', '.')) / 2
  2999. except ValueError:
  3000. self.app.inform.emit(_(
  3001. "[ERROR_NOTCL] Wrong value format entered, "
  3002. "use a number."
  3003. ))
  3004. return
  3005. row = self.ui.geo_tools_table.currentRow()
  3006. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  3007. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  3008. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  3009. new_cutz = float('%.4f' % -new_cutz)
  3010. self.ui.cutz_entry.set_value(new_cutz)
  3011. # store the new CutZ value into storage (self.tools)
  3012. for tooluid_key, tooluid_value in self.tools.items():
  3013. if int(tooluid_key) == tool_uid:
  3014. tooluid_value['data']['cutz'] = new_cutz
  3015. def on_tooltable_cellwidget_change(self):
  3016. cw = self.sender()
  3017. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3018. cw_row = cw_index.row()
  3019. cw_col = cw_index.column()
  3020. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  3021. # store the text of the cellWidget that changed it's index in the self.tools
  3022. for tooluid_key, tooluid_value in self.tools.items():
  3023. if int(tooluid_key) == current_uid:
  3024. cb_txt = cw.currentText()
  3025. if cw_col == 2:
  3026. tooluid_value['offset'] = cb_txt
  3027. if cb_txt == ('Custom'):
  3028. self.ui.tool_offset_entry.show()
  3029. self.ui.tool_offset_lbl.show()
  3030. else:
  3031. self.ui.tool_offset_entry.hide()
  3032. self.ui.tool_offset_lbl.hide()
  3033. # reset the offset_value in storage self.tools
  3034. tooluid_value['offset_value'] = 0.0
  3035. elif cw_col == 3:
  3036. # force toolpath type as 'Iso' if the tool type is V-Shape
  3037. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  3038. tooluid_value['type'] = _('Iso')
  3039. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3040. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3041. else:
  3042. tooluid_value['type'] = cb_txt
  3043. elif cw_col == 4:
  3044. tooluid_value['tool_type'] = cb_txt
  3045. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  3046. if cb_txt == 'V':
  3047. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3048. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3049. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  3050. def update_form(self, dict_storage):
  3051. for form_key in self.form_fields:
  3052. for storage_key in dict_storage:
  3053. if form_key == storage_key:
  3054. try:
  3055. self.form_fields[form_key].set_value(dict_storage[form_key])
  3056. except Exception as e:
  3057. log.debug(str(e))
  3058. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  3059. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  3060. self.ui.ois_dwell_geo.on_cb_change()
  3061. self.ui.ois_mpass_geo.on_cb_change()
  3062. self.ui.ois_tcz_geo.on_cb_change()
  3063. def gui_form_to_storage(self):
  3064. self.ui_disconnect()
  3065. widget_changed = self.sender()
  3066. try:
  3067. widget_idx = self.ui.grid3.indexOf(widget_changed)
  3068. except:
  3069. return
  3070. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  3071. if widget_idx == 1 or widget_idx == 3:
  3072. self.update_cutz()
  3073. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  3074. # ui_diconnect() so I use this 'hack'
  3075. if isinstance(widget_changed, FCCheckBox):
  3076. if widget_changed.text() == 'Multi-Depth:':
  3077. self.ui.ois_mpass_geo.on_cb_change()
  3078. if widget_changed.text() == 'Tool change':
  3079. self.ui.ois_tcz_geo.on_cb_change()
  3080. if widget_changed.text() == 'Dwell:':
  3081. self.ui.ois_dwell_geo.on_cb_change()
  3082. row = self.ui.geo_tools_table.currentRow()
  3083. if row < 0:
  3084. row = 0
  3085. # store all the data associated with the row parameter to the self.tools storage
  3086. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  3087. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  3088. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  3089. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  3090. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3091. try:
  3092. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  3093. except ValueError:
  3094. # try to convert comma to decimal point. if it's still not working error message and return
  3095. try:
  3096. offset_value_item = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3097. )
  3098. except ValueError:
  3099. self.app.inform.emit(_(
  3100. "[ERROR_NOTCL] Wrong value format entered, "
  3101. "use a number."
  3102. ))
  3103. return
  3104. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  3105. temp_tools = {}
  3106. temp_dia = {}
  3107. temp_data = {}
  3108. for tooluid_key, tooluid_value in self.tools.items():
  3109. if int(tooluid_key) == tooluid_item:
  3110. for key, value in tooluid_value.items():
  3111. if key == 'tooldia':
  3112. temp_dia[key] = tooldia_item
  3113. # update the 'offset', 'type' and 'tool_type' sections
  3114. if key == 'offset':
  3115. temp_dia[key] = offset_item
  3116. if key == 'type':
  3117. temp_dia[key] = type_item
  3118. if key == 'tool_type':
  3119. temp_dia[key] = tool_type_item
  3120. if key == 'offset_value':
  3121. temp_dia[key] = offset_value_item
  3122. if key == 'data':
  3123. # update the 'data' section
  3124. for data_key in tooluid_value[key].keys():
  3125. for form_key, form_value in self.form_fields.items():
  3126. if form_key == data_key:
  3127. temp_data[data_key] = form_value.get_value()
  3128. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  3129. # updated from self.app.defaults
  3130. if data_key not in self.form_fields:
  3131. temp_data[data_key] = value[data_key]
  3132. temp_dia[key] = deepcopy(temp_data)
  3133. temp_data.clear()
  3134. if key == 'solid_geometry':
  3135. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3136. temp_tools[tooluid_key] = deepcopy(temp_dia)
  3137. else:
  3138. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  3139. self.tools.clear()
  3140. self.tools = deepcopy(temp_tools)
  3141. temp_tools.clear()
  3142. self.ui_connect()
  3143. def select_tools_table_row(self, row, clearsel=None):
  3144. if clearsel:
  3145. self.ui.geo_tools_table.clearSelection()
  3146. if self.ui.geo_tools_table.rowCount() > 0:
  3147. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  3148. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  3149. def export_dxf(self):
  3150. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3151. dwg = None
  3152. try:
  3153. dwg = ezdxf.new('R2010')
  3154. msp = dwg.modelspace()
  3155. def g2dxf(dxf_space, geo):
  3156. if isinstance(geo, MultiPolygon):
  3157. for poly in geo:
  3158. ext_points = list(poly.exterior.coords)
  3159. dxf_space.add_lwpolyline(ext_points)
  3160. for interior in poly.interiors:
  3161. dxf_space.add_lwpolyline(list(interior.coords))
  3162. if isinstance(geo, Polygon):
  3163. ext_points = list(geo.exterior.coords)
  3164. dxf_space.add_lwpolyline(ext_points)
  3165. for interior in geo.interiors:
  3166. dxf_space.add_lwpolyline(list(interior.coords))
  3167. if isinstance(geo, MultiLineString):
  3168. for line in geo:
  3169. dxf_space.add_lwpolyline(list(line.coords))
  3170. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  3171. dxf_space.add_lwpolyline(list(geo.coords))
  3172. multigeo_solid_geometry = []
  3173. if self.multigeo:
  3174. for tool in self.tools:
  3175. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  3176. else:
  3177. multigeo_solid_geometry = self.solid_geometry
  3178. for geo in multigeo_solid_geometry:
  3179. if type(geo) == list:
  3180. for g in geo:
  3181. g2dxf(msp, g)
  3182. else:
  3183. g2dxf(msp, geo)
  3184. # points = FlatCAMGeometry.get_pts(geo)
  3185. # msp.add_lwpolyline(points)
  3186. except Exception as e:
  3187. log.debug(str(e))
  3188. return dwg
  3189. def get_selected_tools_table_items(self):
  3190. """
  3191. Returns a list of lists, each list in the list is made out of row elements
  3192. :return: List of table_tools items.
  3193. :rtype: list
  3194. """
  3195. table_tools_items = []
  3196. if self.multigeo:
  3197. for x in self.ui.geo_tools_table.selectedItems():
  3198. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  3199. for column in range(0, self.ui.geo_tools_table.columnCount())])
  3200. else:
  3201. for x in self.ui.geo_tools_table.selectedItems():
  3202. r = []
  3203. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  3204. # so we don't read them
  3205. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  3206. # the columns have items that have text but also have items that are widgets
  3207. # for which the text they hold has to be read differently
  3208. try:
  3209. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  3210. except AttributeError:
  3211. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  3212. except:
  3213. pass
  3214. r.append(txt)
  3215. table_tools_items.append(r)
  3216. for item in table_tools_items:
  3217. item[0] = str(item[0])
  3218. return table_tools_items
  3219. def on_pp_changed(self):
  3220. current_pp = self.ui.pp_geometry_name_cb.get_value()
  3221. if current_pp == 'hpgl':
  3222. self.old_pp_state = self.ui.mpass_cb.get_value()
  3223. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  3224. self.ui.mpass_cb.set_value(False)
  3225. self.ui.mpass_cb.setDisabled(True)
  3226. self.ui.toolchangeg_cb.set_value(True)
  3227. self.ui.toolchangeg_cb.setDisabled(True)
  3228. else:
  3229. self.ui.mpass_cb.set_value(self.old_pp_state)
  3230. self.ui.mpass_cb.setDisabled(False)
  3231. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  3232. self.ui.toolchangeg_cb.setDisabled(False)
  3233. if "toolchange_probe" in current_pp.lower():
  3234. self.ui.pdepth_entry.setVisible(True)
  3235. self.ui.pdepth_label.show()
  3236. self.ui.feedrate_probe_entry.setVisible(True)
  3237. self.ui.feedrate_probe_label.show()
  3238. else:
  3239. self.ui.pdepth_entry.setVisible(False)
  3240. self.ui.pdepth_label.hide()
  3241. self.ui.feedrate_probe_entry.setVisible(False)
  3242. self.ui.feedrate_probe_label.hide()
  3243. def on_generatecnc_button_click(self, *args):
  3244. self.app.report_usage("geometry_on_generatecnc_button")
  3245. self.read_form()
  3246. self.sel_tools = {}
  3247. try:
  3248. if self.special_group:
  3249. self.app.inform.emit(_(
  3250. "[WARNING_NOTCL] This Geometry can't be processed because it is %s geometry."
  3251. ) % str(self.special_group))
  3252. return
  3253. except AttributeError:
  3254. pass
  3255. # test to see if we have tools available in the tool table
  3256. if self.ui.geo_tools_table.selectedItems():
  3257. for x in self.ui.geo_tools_table.selectedItems():
  3258. try:
  3259. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  3260. except ValueError:
  3261. # try to convert comma to decimal point. if it's still not working error message and return
  3262. try:
  3263. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  3264. except ValueError:
  3265. self.app.inform.emit(_(
  3266. "[ERROR_NOTCL] Wrong Tool Dia value format entered, "
  3267. "use a number."
  3268. ))
  3269. return
  3270. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  3271. for tooluid_key, tooluid_value in self.tools.items():
  3272. if int(tooluid_key) == tooluid:
  3273. self.sel_tools.update({
  3274. tooluid: deepcopy(tooluid_value)
  3275. })
  3276. self.mtool_gen_cncjob()
  3277. self.ui.geo_tools_table.clearSelection()
  3278. elif self.ui.geo_tools_table.rowCount() == 1:
  3279. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  3280. for tooluid_key, tooluid_value in self.tools.items():
  3281. if int(tooluid_key) == tooluid:
  3282. self.sel_tools.update({
  3283. tooluid: deepcopy(tooluid_value)
  3284. })
  3285. self.mtool_gen_cncjob()
  3286. self.ui.geo_tools_table.clearSelection()
  3287. else:
  3288. self.app.inform.emit(_(
  3289. "[ERROR_NOTCL] Failed. No tool selected in the tool table ..."
  3290. ))
  3291. def mtool_gen_cncjob(self, segx=None, segy=None, use_thread=True):
  3292. """
  3293. Creates a multi-tool CNCJob out of this Geometry object.
  3294. The actual work is done by the target FlatCAMCNCjob object's
  3295. `generate_from_geometry_2()` method.
  3296. :param z_cut: Cut depth (negative)
  3297. :param z_move: Hight of the tool when travelling (not cutting)
  3298. :param feedrate: Feed rate while cutting on X - Y plane
  3299. :param feedrate_z: Feed rate while cutting on Z plane
  3300. :param feedrate_rapid: Feed rate while moving with rapids
  3301. :param tooldia: Tool diameter
  3302. :param outname: Name of the new object
  3303. :param spindlespeed: Spindle speed (RPM)
  3304. :param ppname_g Name of the postprocessor
  3305. :return: None
  3306. """
  3307. offset_str = ''
  3308. multitool_gcode = ''
  3309. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  3310. outname = "%s_%s" % (self.options["name"], 'cnc')
  3311. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3312. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3313. try:
  3314. xmin = self.options['xmin']
  3315. ymin = self.options['ymin']
  3316. xmax = self.options['xmax']
  3317. ymax = self.options['ymax']
  3318. except Exception as e:
  3319. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  3320. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  3321. msg += _('FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s') % str(e)
  3322. msg += traceback.format_exc()
  3323. self.app.inform.emit(msg)
  3324. return
  3325. # Object initialization function for app.new_object()
  3326. # RUNNING ON SEPARATE THREAD!
  3327. def job_init_single_geometry(job_obj, app_obj):
  3328. assert isinstance(job_obj, FlatCAMCNCjob), \
  3329. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3330. # count the tools
  3331. tool_cnt = 0
  3332. dia_cnc_dict = {}
  3333. # this turn on the FlatCAMCNCJob plot for multiple tools
  3334. job_obj.multitool = True
  3335. job_obj.multigeo = False
  3336. job_obj.cnc_tools.clear()
  3337. # job_obj.create_geometry()
  3338. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  3339. job_obj.segx = segx
  3340. job_obj.segy = segy
  3341. try:
  3342. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3343. except ValueError:
  3344. # try to convert comma to decimal point. if it's still not working error message and return
  3345. try:
  3346. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3347. except ValueError:
  3348. self.app.inform.emit(
  3349. _(
  3350. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  3351. ))
  3352. try:
  3353. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3354. except ValueError:
  3355. # try to convert comma to decimal point. if it's still not working error message and return
  3356. try:
  3357. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3358. except ValueError:
  3359. self.app.inform.emit(
  3360. _(
  3361. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  3362. 'or self.options["feedrate_probe"]'
  3363. ))
  3364. for tooluid_key in self.sel_tools:
  3365. tool_cnt += 1
  3366. app_obj.progress.emit(20)
  3367. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3368. if diadict_key == 'tooldia':
  3369. tooldia_val = float('%.4f' % float(diadict_value))
  3370. dia_cnc_dict.update({
  3371. diadict_key: tooldia_val
  3372. })
  3373. if diadict_key == 'offset':
  3374. o_val = diadict_value.lower()
  3375. dia_cnc_dict.update({
  3376. diadict_key: o_val
  3377. })
  3378. if diadict_key == 'type':
  3379. t_val = diadict_value
  3380. dia_cnc_dict.update({
  3381. diadict_key: t_val
  3382. })
  3383. if diadict_key == 'tool_type':
  3384. tt_val = diadict_value
  3385. dia_cnc_dict.update({
  3386. diadict_key: tt_val
  3387. })
  3388. if diadict_key == 'data':
  3389. for data_key, data_value in diadict_value.items():
  3390. if data_key == "multidepth":
  3391. multidepth = data_value
  3392. if data_key == "depthperpass":
  3393. depthpercut = data_value
  3394. if data_key == "extracut":
  3395. extracut = data_value
  3396. if data_key == "startz":
  3397. startz = data_value
  3398. if data_key == "endz":
  3399. endz = data_value
  3400. if data_key == "toolchangez":
  3401. toolchangez =data_value
  3402. if data_key == "toolchangexy":
  3403. toolchangexy = data_value
  3404. if data_key == "toolchange":
  3405. toolchange = data_value
  3406. if data_key == "cutz":
  3407. z_cut = data_value
  3408. if data_key == "travelz":
  3409. z_move = data_value
  3410. if data_key == "feedrate":
  3411. feedrate = data_value
  3412. if data_key == "feedrate_z":
  3413. feedrate_z = data_value
  3414. if data_key == "feedrate_rapid":
  3415. feedrate_rapid = data_value
  3416. if data_key == "ppname_g":
  3417. pp_geometry_name = data_value
  3418. if data_key == "spindlespeed":
  3419. spindlespeed = data_value
  3420. if data_key == "dwell":
  3421. dwell = data_value
  3422. if data_key == "dwelltime":
  3423. dwelltime = data_value
  3424. datadict = deepcopy(diadict_value)
  3425. dia_cnc_dict.update({
  3426. diadict_key: datadict
  3427. })
  3428. if dia_cnc_dict['offset'] == ('in'):
  3429. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3430. offset_str = 'inside'
  3431. elif dia_cnc_dict['offset'].lower() == ('out'):
  3432. tool_offset = dia_cnc_dict['tooldia'] / 2
  3433. offset_str = 'outside'
  3434. elif dia_cnc_dict['offset'].lower() == ('path'):
  3435. offset_str = 'onpath'
  3436. tool_offset = 0.0
  3437. else:
  3438. offset_str = 'custom'
  3439. try:
  3440. offset_value = float(self.ui.tool_offset_entry.get_value())
  3441. except ValueError:
  3442. # try to convert comma to decimal point. if it's still not working error message and return
  3443. try:
  3444. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3445. )
  3446. except ValueError:
  3447. self.app.inform.emit(_(
  3448. "[ERROR_NOTCL] Wrong value format entered, "
  3449. "use a number."
  3450. ))
  3451. return
  3452. if offset_value:
  3453. tool_offset = float(offset_value)
  3454. else:
  3455. self.app.inform.emit(
  3456. _(
  3457. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3458. "Add a Tool Offset or change the Offset Type."
  3459. )
  3460. )
  3461. return
  3462. dia_cnc_dict.update({
  3463. 'offset_value': tool_offset
  3464. })
  3465. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3466. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3467. # Propagate options
  3468. job_obj.options["tooldia"] = tooldia_val
  3469. job_obj.options['type'] = 'Geometry'
  3470. job_obj.options['tool_dia'] = tooldia_val
  3471. job_obj.options['xmin'] = xmin
  3472. job_obj.options['ymin'] = ymin
  3473. job_obj.options['xmax'] = xmax
  3474. job_obj.options['ymax'] = ymax
  3475. app_obj.progress.emit(40)
  3476. res = job_obj.generate_from_geometry_2(
  3477. self, tooldia=tooldia_val, offset=tool_offset, tolerance=0.0005,
  3478. z_cut=z_cut, z_move=z_move,
  3479. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3480. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3481. multidepth=multidepth, depthpercut=depthpercut,
  3482. extracut=extracut, startz=startz, endz=endz,
  3483. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3484. pp_geometry_name=pp_geometry_name,
  3485. tool_no=tool_cnt)
  3486. if res == 'fail':
  3487. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3488. return 'fail'
  3489. else:
  3490. dia_cnc_dict['gcode'] = res
  3491. app_obj.progress.emit(50)
  3492. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3493. # object is the source of gcode
  3494. job_obj.toolchange_xy_type = "geometry"
  3495. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3496. # TODO this serve for bounding box creation only; should be optimized
  3497. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3498. app_obj.progress.emit(80)
  3499. job_obj.cnc_tools.update({
  3500. tooluid_key: deepcopy(dia_cnc_dict)
  3501. })
  3502. dia_cnc_dict.clear()
  3503. # Object initialization function for app.new_object()
  3504. # RUNNING ON SEPARATE THREAD!
  3505. def job_init_multi_geometry(job_obj, app_obj):
  3506. assert isinstance(job_obj, FlatCAMCNCjob), \
  3507. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3508. # count the tools
  3509. tool_cnt = 0
  3510. dia_cnc_dict = {}
  3511. current_uid = int(1)
  3512. # this turn on the FlatCAMCNCJob plot for multiple tools
  3513. job_obj.multitool = True
  3514. job_obj.multigeo = True
  3515. job_obj.cnc_tools.clear()
  3516. job_obj.options['xmin'] = xmin
  3517. job_obj.options['ymin'] = ymin
  3518. job_obj.options['xmax'] = xmax
  3519. job_obj.options['ymax'] = ymax
  3520. try:
  3521. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3522. except ValueError:
  3523. # try to convert comma to decimal point. if it's still not working error message and return
  3524. try:
  3525. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3526. except ValueError:
  3527. self.app.inform.emit(
  3528. _(
  3529. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  3530. ))
  3531. try:
  3532. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3533. except ValueError:
  3534. # try to convert comma to decimal point. if it's still not working error message and return
  3535. try:
  3536. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3537. except ValueError:
  3538. self.app.inform.emit(
  3539. _(
  3540. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  3541. 'or self.options["feedrate_probe"]'
  3542. ))
  3543. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  3544. if not self.solid_geometry:
  3545. a = 0
  3546. for tooluid_key in self.tools:
  3547. if self.tools[tooluid_key]['solid_geometry'] is None:
  3548. a += 1
  3549. if a == len(self.tools):
  3550. self.app.inform.emit(_(
  3551. '[ERROR_NOTCL] Cancelled. Empty file, it has no geometry...'
  3552. ))
  3553. return 'fail'
  3554. for tooluid_key in self.sel_tools:
  3555. tool_cnt += 1
  3556. app_obj.progress.emit(20)
  3557. # find the tool_dia associated with the tooluid_key
  3558. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  3559. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  3560. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  3561. for k, v in self.tools.items():
  3562. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  3563. current_uid = int(k)
  3564. break
  3565. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3566. if diadict_key == 'tooldia':
  3567. tooldia_val = float('%.4f' % float(diadict_value))
  3568. dia_cnc_dict.update({
  3569. diadict_key: tooldia_val
  3570. })
  3571. if diadict_key == 'offset':
  3572. o_val = diadict_value.lower()
  3573. dia_cnc_dict.update({
  3574. diadict_key: o_val
  3575. })
  3576. if diadict_key == 'type':
  3577. t_val = diadict_value
  3578. dia_cnc_dict.update({
  3579. diadict_key: t_val
  3580. })
  3581. if diadict_key == 'tool_type':
  3582. tt_val = diadict_value
  3583. dia_cnc_dict.update({
  3584. diadict_key: tt_val
  3585. })
  3586. if diadict_key == 'data':
  3587. for data_key, data_value in diadict_value.items():
  3588. if data_key == "multidepth":
  3589. multidepth = data_value
  3590. if data_key == "depthperpass":
  3591. depthpercut = data_value
  3592. if data_key == "extracut":
  3593. extracut = data_value
  3594. if data_key == "startz":
  3595. startz = data_value
  3596. if data_key == "endz":
  3597. endz = data_value
  3598. if data_key == "toolchangez":
  3599. toolchangez =data_value
  3600. if data_key == "toolchangexy":
  3601. toolchangexy = data_value
  3602. if data_key == "toolchange":
  3603. toolchange = data_value
  3604. if data_key == "cutz":
  3605. z_cut = data_value
  3606. if data_key == "travelz":
  3607. z_move = data_value
  3608. if data_key == "feedrate":
  3609. feedrate = data_value
  3610. if data_key == "feedrate_z":
  3611. feedrate_z = data_value
  3612. if data_key == "feedrate_rapid":
  3613. feedrate_rapid = data_value
  3614. if data_key == "ppname_g":
  3615. pp_geometry_name = data_value
  3616. if data_key == "spindlespeed":
  3617. spindlespeed = data_value
  3618. if data_key == "dwell":
  3619. dwell = data_value
  3620. if data_key == "dwelltime":
  3621. dwelltime = data_value
  3622. datadict = deepcopy(diadict_value)
  3623. dia_cnc_dict.update({
  3624. diadict_key: datadict
  3625. })
  3626. if dia_cnc_dict['offset'] == ('in'):
  3627. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3628. offset_str = 'inside'
  3629. elif dia_cnc_dict['offset'].lower() == ('out'):
  3630. tool_offset = dia_cnc_dict['tooldia'] / 2
  3631. offset_str = 'outside'
  3632. elif dia_cnc_dict['offset'].lower() == ('path'):
  3633. offset_str = 'onpath'
  3634. tool_offset = 0.0
  3635. else:
  3636. offset_str = 'custom'
  3637. try:
  3638. offset_value = float(self.ui.tool_offset_entry.get_value())
  3639. except ValueError:
  3640. # try to convert comma to decimal point. if it's still not working error message and return
  3641. try:
  3642. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3643. )
  3644. except ValueError:
  3645. self.app.inform.emit(_(
  3646. "[ERROR_NOTCL] Wrong value format entered, "
  3647. "use a number."
  3648. ))
  3649. return
  3650. if offset_value:
  3651. tool_offset = float(offset_value)
  3652. else:
  3653. self.app.inform.emit(
  3654. _(
  3655. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3656. "Add a Tool Offset or change the Offset Type."
  3657. )
  3658. )
  3659. return
  3660. dia_cnc_dict.update({
  3661. 'offset_value': tool_offset
  3662. })
  3663. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3664. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3665. # Propagate options
  3666. job_obj.options["tooldia"] = tooldia_val
  3667. job_obj.options['type'] = 'Geometry'
  3668. job_obj.options['tool_dia'] = tooldia_val
  3669. app_obj.progress.emit(40)
  3670. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  3671. res = job_obj.generate_from_multitool_geometry(
  3672. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  3673. tolerance=0.0005, z_cut=z_cut, z_move=z_move,
  3674. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3675. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3676. multidepth=multidepth, depthpercut=depthpercut,
  3677. extracut=extracut, startz=startz, endz=endz,
  3678. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3679. pp_geometry_name=pp_geometry_name,
  3680. tool_no=tool_cnt)
  3681. if res == 'fail':
  3682. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3683. return 'fail'
  3684. else:
  3685. dia_cnc_dict['gcode'] = res
  3686. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3687. # TODO this serve for bounding box creation only; should be optimized
  3688. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3689. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3690. # object is the source of gcode
  3691. job_obj.toolchange_xy_type = "geometry"
  3692. app_obj.progress.emit(80)
  3693. job_obj.cnc_tools.update({
  3694. tooluid_key: deepcopy(dia_cnc_dict)
  3695. })
  3696. dia_cnc_dict.clear()
  3697. if use_thread:
  3698. # To be run in separate thread
  3699. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  3700. # separate solid_geometry in the self.tools dictionary
  3701. def job_thread(app_obj):
  3702. if self.solid_geometry:
  3703. with self.app.proc_container.new(_("Generating CNC Code")):
  3704. if app_obj.new_object("cncjob", outname, job_init_single_geometry) != 'fail':
  3705. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  3706. app_obj.progress.emit(100)
  3707. else:
  3708. with self.app.proc_container.new(_("Generating CNC Code")):
  3709. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  3710. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  3711. app_obj.progress.emit(100)
  3712. # Create a promise with the name
  3713. self.app.collection.promise(outname)
  3714. # Send to worker
  3715. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3716. else:
  3717. if self.solid_geometry:
  3718. self.app.new_object("cncjob", outname, job_init_single_geometry)
  3719. else:
  3720. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  3721. def generatecncjob(self, outname=None,
  3722. tooldia=None, offset=None,
  3723. z_cut=None, z_move=None,
  3724. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  3725. spindlespeed=None, dwell=None, dwelltime=None,
  3726. multidepth=None, depthperpass=None,
  3727. toolchange=None, toolchangez=None, toolchangexy=None,
  3728. extracut=None, startz=None, endz=None,
  3729. ppname_g=None,
  3730. segx=None,
  3731. segy=None,
  3732. use_thread=True):
  3733. """
  3734. Only used for TCL Command.
  3735. Creates a CNCJob out of this Geometry object. The actual
  3736. work is done by the target FlatCAMCNCjob object's
  3737. `generate_from_geometry_2()` method.
  3738. :param z_cut: Cut depth (negative)
  3739. :param z_move: Hight of the tool when travelling (not cutting)
  3740. :param feedrate: Feed rate while cutting on X - Y plane
  3741. :param feedrate_z: Feed rate while cutting on Z plane
  3742. :param feedrate_rapid: Feed rate while moving with rapids
  3743. :param tooldia: Tool diameter
  3744. :param outname: Name of the new object
  3745. :param spindlespeed: Spindle speed (RPM)
  3746. :param ppname_g Name of the postprocessor
  3747. :return: None
  3748. """
  3749. tooldia = tooldia if tooldia else float(self.options["cnctooldia"])
  3750. outname = outname if outname is not None else self.options["name"]
  3751. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  3752. z_move = z_move if z_move is not None else float(self.options["travelz"])
  3753. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  3754. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  3755. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  3756. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  3757. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  3758. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3759. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3760. extracut = extracut if extracut is not None else float(self.options["extracut"])
  3761. startz = startz if startz is not None else self.options["startz"]
  3762. endz = endz if endz is not None else float(self.options["endz"])
  3763. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  3764. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  3765. toolchange = toolchange if toolchange else self.options["toolchange"]
  3766. offset = offset if offset else 0.0
  3767. # int or None.
  3768. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  3769. dwell = dwell if dwell else self.options["dwell"]
  3770. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  3771. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  3772. # Object initialization function for app.new_object()
  3773. # RUNNING ON SEPARATE THREAD!
  3774. def job_init(job_obj, app_obj):
  3775. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3776. # Propagate options
  3777. job_obj.options["tooldia"] = tooldia
  3778. app_obj.progress.emit(20)
  3779. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3780. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3781. app_obj.progress.emit(40)
  3782. job_obj.options['type'] = 'Geometry'
  3783. job_obj.options['tool_dia'] = tooldia
  3784. job_obj.segx = segx
  3785. job_obj.segy = segy
  3786. try:
  3787. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3788. except ValueError:
  3789. # try to convert comma to decimal point. if it's still not working error message and return
  3790. try:
  3791. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3792. except ValueError:
  3793. self.app.inform.emit(
  3794. _(
  3795. '[ERROR_NOTCL] Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]'
  3796. ))
  3797. try:
  3798. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3799. except ValueError:
  3800. # try to convert comma to decimal point. if it's still not working error message and return
  3801. try:
  3802. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3803. except ValueError:
  3804. self.app.inform.emit(
  3805. _(
  3806. '[ERROR_NOTCL] Wrong value format for self.defaults["feedrate_probe"] '
  3807. 'or self.options["feedrate_probe"]'
  3808. ))
  3809. # TODO: The tolerance should not be hard coded. Just for testing.
  3810. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=0.0005,
  3811. z_cut=z_cut, z_move=z_move,
  3812. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3813. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3814. multidepth=multidepth, depthpercut=depthperpass,
  3815. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3816. extracut=extracut, startz=startz, endz=endz,
  3817. pp_geometry_name=ppname_g
  3818. )
  3819. app_obj.progress.emit(50)
  3820. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  3821. # source of gcode
  3822. job_obj.toolchange_xy_type = "geometry"
  3823. job_obj.gcode_parse()
  3824. app_obj.progress.emit(80)
  3825. if use_thread:
  3826. # To be run in separate thread
  3827. def job_thread(app_obj):
  3828. with self.app.proc_container.new(_("Generating CNC Code")):
  3829. app_obj.new_object("cncjob", outname, job_init)
  3830. app_obj.inform.emit("[success] CNCjob created: %s" % outname)
  3831. app_obj.progress.emit(100)
  3832. # Create a promise with the name
  3833. self.app.collection.promise(outname)
  3834. # Send to worker
  3835. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3836. else:
  3837. self.app.new_object("cncjob", outname, job_init)
  3838. # def on_plot_cb_click(self, *args): # TODO: args not needed
  3839. # if self.muted_ui:
  3840. # return
  3841. # self.read_form_item('plot')
  3842. def scale(self, xfactor, yfactor=None, point=None):
  3843. """
  3844. Scales all geometry by a given factor.
  3845. :param xfactor: Factor by which to scale the object's geometry/
  3846. :type xfactor: float
  3847. :param yfactor: Factor by which to scale the object's geometry/
  3848. :type yfactor: float
  3849. :return: None
  3850. :rtype: None
  3851. """
  3852. try:
  3853. xfactor = float(xfactor)
  3854. except:
  3855. self.app.inform.emit(_(
  3856. "[ERROR_NOTCL] Scale factor has to be a number: integer or float."))
  3857. return
  3858. if yfactor is None:
  3859. yfactor = xfactor
  3860. else:
  3861. try:
  3862. yfactor = float(yfactor)
  3863. except:
  3864. self.app.inform.emit(_(
  3865. "[ERROR_NOTCL] Scale factor has to be a number: integer or float."
  3866. ))
  3867. return
  3868. if point is None:
  3869. px = 0
  3870. py = 0
  3871. else:
  3872. px, py = point
  3873. # if type(self.solid_geometry) == list:
  3874. # geo_list = self.flatten(self.solid_geometry)
  3875. # self.solid_geometry = []
  3876. # # for g in geo_list:
  3877. # # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  3878. # self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  3879. # for g in geo_list]
  3880. # else:
  3881. # self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  3882. # origin=(px, py))
  3883. # self.app.inform.emit("[success] Geometry Scale done.")
  3884. def scale_recursion(geom):
  3885. if type(geom) == list:
  3886. geoms=list()
  3887. for local_geom in geom:
  3888. geoms.append(scale_recursion(local_geom))
  3889. return geoms
  3890. else:
  3891. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  3892. if self.multigeo is True:
  3893. for tool in self.tools:
  3894. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  3895. else:
  3896. self.solid_geometry=scale_recursion(self.solid_geometry)
  3897. self.app.inform.emit(_(
  3898. "[success] Geometry Scale done."
  3899. ))
  3900. def offset(self, vect):
  3901. """
  3902. Offsets all geometry by a given vector/
  3903. :param vect: (x, y) vector by which to offset the object's geometry.
  3904. :type vect: tuple
  3905. :return: None
  3906. :rtype: None
  3907. """
  3908. try:
  3909. dx, dy = vect
  3910. except TypeError:
  3911. self.app.inform.emit(_(
  3912. "[ERROR_NOTCL] An (x,y) pair of values are needed. "
  3913. "Probable you entered only one value in the Offset field."
  3914. ))
  3915. return
  3916. def translate_recursion(geom):
  3917. if type(geom) == list:
  3918. geoms=list()
  3919. for local_geom in geom:
  3920. geoms.append(translate_recursion(local_geom))
  3921. return geoms
  3922. else:
  3923. return affinity.translate(geom, xoff=dx, yoff=dy)
  3924. if self.multigeo is True:
  3925. for tool in self.tools:
  3926. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  3927. else:
  3928. self.solid_geometry=translate_recursion(self.solid_geometry)
  3929. self.app.inform.emit(_(
  3930. "[success] Geometry Offset done."
  3931. ))
  3932. def convert_units(self, units):
  3933. self.ui_disconnect()
  3934. factor = Geometry.convert_units(self, units)
  3935. self.options['cutz'] = float(self.options['cutz']) * factor
  3936. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  3937. self.options['travelz'] = float(self.options['travelz']) * factor
  3938. self.options['feedrate'] = float(self.options['feedrate']) * factor
  3939. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  3940. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  3941. self.options['endz'] = float(self.options['endz']) * factor
  3942. # self.options['cnctooldia'] *= factor
  3943. # self.options['painttooldia'] *= factor
  3944. # self.options['paintmargin'] *= factor
  3945. # self.options['paintoverlap'] *= factor
  3946. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  3947. if self.app.defaults["geometry_toolchangexy"] == '':
  3948. self.options['toolchangexy'] = "0.0, 0.0"
  3949. else:
  3950. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  3951. if len(coords_xy) < 2:
  3952. self.app.inform.emit(_(
  3953. "[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  3954. "in the format (x, y) \nbut now there is only one value, not two. "
  3955. ))
  3956. return 'fail'
  3957. coords_xy[0] *= factor
  3958. coords_xy[1] *= factor
  3959. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3960. if self.options['startz'] is not None:
  3961. self.options['startz'] = float(self.options['startz']) * factor
  3962. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  3963. 'endz', 'toolchangez']
  3964. if isinstance(self, FlatCAMGeometry):
  3965. temp_tools_dict = {}
  3966. tool_dia_copy = {}
  3967. data_copy = {}
  3968. for tooluid_key, tooluid_value in self.tools.items():
  3969. for dia_key, dia_value in tooluid_value.items():
  3970. if dia_key == 'tooldia':
  3971. dia_value *= factor
  3972. dia_value = float('%.4f' % dia_value)
  3973. tool_dia_copy[dia_key] = dia_value
  3974. if dia_key == 'offset':
  3975. tool_dia_copy[dia_key] = dia_value
  3976. if dia_key == 'offset_value':
  3977. dia_value *= factor
  3978. tool_dia_copy[dia_key] = dia_value
  3979. # convert the value in the Custom Tool Offset entry in UI
  3980. custom_offset = None
  3981. try:
  3982. custom_offset = float(self.ui.tool_offset_entry.get_value())
  3983. except ValueError:
  3984. # try to convert comma to decimal point. if it's still not working error message and return
  3985. try:
  3986. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3987. )
  3988. except ValueError:
  3989. self.app.inform.emit(_(
  3990. "[ERROR_NOTCL] Wrong value format entered, "
  3991. "use a number."
  3992. ))
  3993. return
  3994. except TypeError:
  3995. pass
  3996. if custom_offset:
  3997. custom_offset *= factor
  3998. self.ui.tool_offset_entry.set_value(custom_offset)
  3999. if dia_key == 'type':
  4000. tool_dia_copy[dia_key] = dia_value
  4001. if dia_key == 'tool_type':
  4002. tool_dia_copy[dia_key] = dia_value
  4003. if dia_key == 'data':
  4004. for data_key, data_value in dia_value.items():
  4005. # convert the form fields that are convertible
  4006. for param in param_list:
  4007. if data_key == param and data_value is not None:
  4008. data_copy[data_key] = data_value * factor
  4009. # copy the other dict entries that are not convertible
  4010. if data_key not in param_list:
  4011. data_copy[data_key] = data_value
  4012. tool_dia_copy[dia_key] = deepcopy(data_copy)
  4013. data_copy.clear()
  4014. temp_tools_dict.update({
  4015. tooluid_key: deepcopy(tool_dia_copy)
  4016. })
  4017. tool_dia_copy.clear()
  4018. self.tools.clear()
  4019. self.tools = deepcopy(temp_tools_dict)
  4020. # if there is a value in the new tool field then convert that one too
  4021. tooldia = self.ui.addtool_entry.get_value()
  4022. if tooldia:
  4023. tooldia *= factor
  4024. # limit the decimals to 2 for METRIC and 3 for INCH
  4025. if units.lower() == 'in':
  4026. tooldia = float('%.4f' % tooldia)
  4027. else:
  4028. tooldia = float('%.2f' % tooldia)
  4029. self.ui.addtool_entry.set_value(tooldia)
  4030. return factor
  4031. def plot_element(self, element, color='red', visible=None):
  4032. visible = visible if visible else self.options['plot']
  4033. try:
  4034. for sub_el in element:
  4035. self.plot_element(sub_el)
  4036. except TypeError: # Element is not iterable...
  4037. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  4038. def plot(self, visible=None, kind=None):
  4039. """
  4040. Plot the object.
  4041. :param visible: Controls if the added shape is visible of not
  4042. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  4043. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  4044. :return:
  4045. """
  4046. # Does all the required setup and returns False
  4047. # if the 'ptint' option is set to False.
  4048. if not FlatCAMObj.plot(self):
  4049. return
  4050. try:
  4051. # plot solid geometries found as members of self.tools attribute dict
  4052. # for MultiGeo
  4053. if self.multigeo == True: # geo multi tool usage
  4054. for tooluid_key in self.tools:
  4055. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4056. self.plot_element(solid_geometry, visible=visible)
  4057. # plot solid geometry that may be an direct attribute of the geometry object
  4058. # for SingleGeo
  4059. if self.solid_geometry:
  4060. self.plot_element(self.solid_geometry, visible=visible)
  4061. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  4062. self.shapes.redraw()
  4063. except (ObjectDeleted, AttributeError):
  4064. self.shapes.clear(update=True)
  4065. def on_plot_cb_click(self, *args):
  4066. if self.muted_ui:
  4067. return
  4068. self.plot()
  4069. self.read_form_item('plot')
  4070. self.ui_disconnect()
  4071. cb_flag = self.ui.plot_cb.isChecked()
  4072. for row in range(self.ui.geo_tools_table.rowCount()):
  4073. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  4074. if cb_flag:
  4075. table_cb.setChecked(True)
  4076. else:
  4077. table_cb.setChecked(False)
  4078. self.ui_connect()
  4079. def on_plot_cb_click_table(self):
  4080. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4081. self.ui_disconnect()
  4082. cw = self.sender()
  4083. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  4084. cw_row = cw_index.row()
  4085. check_row = 0
  4086. self.shapes.clear(update=True)
  4087. for tooluid_key in self.tools:
  4088. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4089. # find the geo_tool_table row associated with the tooluid_key
  4090. for row in range(self.ui.geo_tools_table.rowCount()):
  4091. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  4092. if tooluid_item == int(tooluid_key):
  4093. check_row = row
  4094. break
  4095. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  4096. self.plot_element(element=solid_geometry, visible=True)
  4097. self.shapes.redraw()
  4098. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4099. # if all the row plot's are enabled also enable the general plot checkbox
  4100. cb_cnt = 0
  4101. total_row = self.ui.geo_tools_table.rowCount()
  4102. for row in range(total_row):
  4103. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  4104. cb_cnt += 1
  4105. else:
  4106. cb_cnt -= 1
  4107. if cb_cnt < total_row:
  4108. self.ui.plot_cb.setChecked(False)
  4109. else:
  4110. self.ui.plot_cb.setChecked(True)
  4111. self.ui_connect()
  4112. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  4113. """
  4114. Represents G-Code.
  4115. """
  4116. optionChanged = QtCore.pyqtSignal(str)
  4117. ui_type = CNCObjectUI
  4118. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  4119. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  4120. spindlespeed=None):
  4121. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  4122. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  4123. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  4124. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  4125. FlatCAMObj.__init__(self, name)
  4126. self.kind = "cncjob"
  4127. self.options.update({
  4128. "plot": True,
  4129. "tooldia": 0.03937, # 0.4mm in inches
  4130. "append": "",
  4131. "prepend": "",
  4132. "dwell": False,
  4133. "dwelltime": 1,
  4134. "type": 'Geometry',
  4135. "toolchange_macro": '',
  4136. "toolchange_macro_enable": False
  4137. })
  4138. '''
  4139. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4140. diameter of the tools and the value is another dict that will hold the data under the following form:
  4141. {tooldia: {
  4142. 'tooluid': 1,
  4143. 'offset': 'Path',
  4144. 'type_item': 'Rough',
  4145. 'tool_type': 'C1',
  4146. 'data': {} # a dict to hold the parameters
  4147. 'gcode': "" # a string with the actual GCODE
  4148. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  4149. 'solid_geometry': []
  4150. },
  4151. ...
  4152. }
  4153. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  4154. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  4155. '''
  4156. self.cnc_tools = {}
  4157. '''
  4158. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  4159. diameter of the tools and the value is another dict that will hold the data under the following form:
  4160. {tooldia: {
  4161. 'tool': int,
  4162. 'nr_drills': int,
  4163. 'nr_slots': int,
  4164. 'offset': float,
  4165. 'data': {} # a dict to hold the parameters
  4166. 'gcode': "" # a string with the actual GCODE
  4167. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  4168. 'solid_geometry': []
  4169. },
  4170. ...
  4171. }
  4172. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  4173. it's done in camlib.Excellon.generate_from_excellon_by_tool()
  4174. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  4175. '''
  4176. self.exc_cnc_tools = {}
  4177. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  4178. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  4179. self.special_group = None
  4180. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  4181. # (like the one in the TCL Command), False
  4182. self.multitool = False
  4183. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  4184. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  4185. self.g_x_re = re.compile(gcodex_re_string)
  4186. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  4187. self.g_y_re = re.compile(gcodey_re_string)
  4188. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  4189. self.g_z_re = re.compile(gcodez_re_string)
  4190. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  4191. self.g_f_re = re.compile(gcodef_re_string)
  4192. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  4193. self.g_t_re = re.compile(gcodet_re_string)
  4194. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  4195. self.g_nr_re = re.compile(gcodenr_re_string)
  4196. # Attributes to be included in serialization
  4197. # Always append to it because it carries contents
  4198. # from predecessors.
  4199. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  4200. self.annotation = self.app.plotcanvas.new_text_group()
  4201. def build_ui(self):
  4202. self.ui_disconnect()
  4203. FlatCAMObj.build_ui(self)
  4204. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  4205. if self.cnc_tools:
  4206. self.ui.cnc_tools_table.show()
  4207. else:
  4208. self.ui.cnc_tools_table.hide()
  4209. offset = 0
  4210. tool_idx = 0
  4211. n = len(self.cnc_tools)
  4212. self.ui.cnc_tools_table.setRowCount(n)
  4213. for dia_key, dia_value in self.cnc_tools.items():
  4214. tool_idx += 1
  4215. row_no = tool_idx - 1
  4216. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  4217. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4218. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  4219. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  4220. # There are no tool bits in MM with more than 2 decimals diameter.
  4221. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  4222. if self.units == 'MM':
  4223. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  4224. else:
  4225. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  4226. offset_txt = list(str(dia_value['offset']))
  4227. offset_txt[0] = offset_txt[0].upper()
  4228. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  4229. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  4230. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  4231. id.setFlags(QtCore.Qt.ItemIsEnabled)
  4232. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4233. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4234. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4235. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  4236. # hack so the checkbox stay centered in the table cell
  4237. # used this:
  4238. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  4239. # plot_item = QtWidgets.QWidget()
  4240. # checkbox = FCCheckBox()
  4241. # checkbox.setCheckState(QtCore.Qt.Checked)
  4242. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  4243. # qhboxlayout.addWidget(checkbox)
  4244. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  4245. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  4246. plot_item = FCCheckBox()
  4247. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  4248. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  4249. if self.ui.plot_cb.isChecked():
  4250. plot_item.setChecked(True)
  4251. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  4252. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  4253. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  4254. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  4255. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  4256. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  4257. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  4258. # make the diameter column editable
  4259. # for row in range(tool_idx):
  4260. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  4261. # QtCore.Qt.ItemIsEnabled)
  4262. for row in range(tool_idx):
  4263. self.ui.cnc_tools_table.item(row, 0).setFlags(
  4264. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  4265. self.ui.cnc_tools_table.resizeColumnsToContents()
  4266. self.ui.cnc_tools_table.resizeRowsToContents()
  4267. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  4268. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  4269. vertical_header.hide()
  4270. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4271. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  4272. horizontal_header.setMinimumSectionSize(10)
  4273. horizontal_header.setDefaultSectionSize(70)
  4274. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  4275. horizontal_header.resizeSection(0, 20)
  4276. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  4277. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  4278. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  4279. horizontal_header.resizeSection(4, 40)
  4280. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  4281. horizontal_header.resizeSection(4, 17)
  4282. # horizontal_header.setStretchLastSection(True)
  4283. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4284. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  4285. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  4286. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  4287. # self.ui.geo_tools_table.setSortingEnabled(True)
  4288. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  4289. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  4290. self.ui_connect()
  4291. def set_ui(self, ui):
  4292. FlatCAMObj.set_ui(self, ui)
  4293. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  4294. assert isinstance(self.ui, CNCObjectUI), \
  4295. "Expected a CNCObjectUI, got %s" % type(self.ui)
  4296. # this signal has to be connected to it's slot before the defaults are populated
  4297. # the decision done in the slot has to override the default value set bellow
  4298. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  4299. self.form_fields.update({
  4300. "plot": self.ui.plot_cb,
  4301. # "tooldia": self.ui.tooldia_entry,
  4302. "append": self.ui.append_text,
  4303. "prepend": self.ui.prepend_text,
  4304. "toolchange_macro": self.ui.toolchange_text,
  4305. "toolchange_macro_enable": self.ui.toolchange_cb
  4306. })
  4307. # Fill form fields only on object create
  4308. self.to_form()
  4309. # this means that the object that created this CNCJob was an Excellon
  4310. try:
  4311. if self.travel_distance:
  4312. self.ui.t_distance_label.show()
  4313. self.ui.t_distance_entry.setVisible(True)
  4314. self.ui.t_distance_entry.setDisabled(True)
  4315. self.ui.t_distance_entry.set_value('%.4f' % float(self.travel_distance))
  4316. self.ui.units_label.setText(str(self.units).lower())
  4317. self.ui.units_label.setDisabled(True)
  4318. except AttributeError:
  4319. pass
  4320. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  4321. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  4322. # Show/Hide Advanced Options
  4323. if self.app.defaults["global_app_level"] == 'b':
  4324. self.ui.level.setText(_(
  4325. '<span style="color:green;"><b>Basic</b></span>'
  4326. ))
  4327. self.ui.cnc_frame.hide()
  4328. else:
  4329. self.ui.level.setText(_(
  4330. '<span style="color:red;"><b>Advanced</b></span>'
  4331. ))
  4332. self.ui.cnc_frame.show()
  4333. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  4334. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  4335. self.ui.modify_gcode_button.clicked.connect(self.on_edit_code_click)
  4336. self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  4337. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  4338. def on_cnc_custom_parameters(self, signal_text):
  4339. if signal_text == 'Parameters':
  4340. return
  4341. else:
  4342. self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4343. def ui_connect(self):
  4344. for row in range(self.ui.cnc_tools_table.rowCount()):
  4345. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  4346. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  4347. def ui_disconnect(self):
  4348. for row in range(self.ui.cnc_tools_table.rowCount()):
  4349. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  4350. try:
  4351. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  4352. except:
  4353. pass
  4354. def on_updateplot_button_click(self, *args):
  4355. """
  4356. Callback for the "Updata Plot" button. Reads the form for updates
  4357. and plots the object.
  4358. """
  4359. self.read_form()
  4360. self.plot()
  4361. def on_plot_kind_change(self):
  4362. kind = self.ui.cncplot_method_combo.get_value()
  4363. self.plot(kind=kind)
  4364. def on_exportgcode_button_click(self, *args):
  4365. self.app.report_usage("cncjob_on_exportgcode_button")
  4366. self.read_form()
  4367. name = self.app.collection.get_active().options['name']
  4368. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4369. _filter_ = "RML1 Files (*.rol);;" \
  4370. "All Files (*.*)"
  4371. elif 'hpgl' in self.pp_geometry_name:
  4372. _filter_ = "HPGL Files (*.plt);;" \
  4373. "All Files (*.*)"
  4374. else:
  4375. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  4376. "G-Code Files (*.g-code);;All Files (*.*)"
  4377. try:
  4378. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  4379. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4380. caption=_("Export Machine Code ..."),
  4381. directory=dir_file_to_save,
  4382. filter=_filter_
  4383. )
  4384. except TypeError:
  4385. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Machine Code ..."), filter=_filter_)
  4386. filename = str(filename)
  4387. if filename == '':
  4388. self.app.inform.emit(_(
  4389. "[WARNING_NOTCL] Export Machine Code cancelled ..."))
  4390. return
  4391. preamble = str(self.ui.prepend_text.get_value())
  4392. postamble = str(self.ui.append_text.get_value())
  4393. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  4394. if gc == 'fail':
  4395. return
  4396. self.app.file_saved.emit("gcode", filename)
  4397. self.app.inform.emit(_("[success] Machine Code file saved to: %s") % filename)
  4398. def on_edit_code_click(self, *args):
  4399. preamble = str(self.ui.prepend_text.get_value())
  4400. postamble = str(self.ui.append_text.get_value())
  4401. gc = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  4402. if gc == 'fail':
  4403. return
  4404. else:
  4405. self.app.gcode_edited = gc
  4406. self.app.init_code_editor(name=_("Code Editor"))
  4407. self.app.ui.buttonOpen.clicked.connect(self.app.handleOpen)
  4408. self.app.ui.buttonSave.clicked.connect(self.app.handleSaveGCode)
  4409. # then append the text from GCode to the text editor
  4410. try:
  4411. for line in self.app.gcode_edited:
  4412. proc_line = str(line).strip('\n')
  4413. self.app.ui.code_editor.append(proc_line)
  4414. except Exception as e:
  4415. log.debug('FlatCAMCNNJob.on_edit_code_click() -->%s' % str(e))
  4416. self.app.inform.emit(_('[ERROR]FlatCAMCNNJob.on_edit_code_click() -->%s') % str(e))
  4417. return
  4418. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4419. self.app.handleTextChanged()
  4420. self.app.ui.show()
  4421. def gcode_header(self):
  4422. log.debug("FlatCAMCNCJob.gcode_header()")
  4423. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4424. marlin = False
  4425. hpgl = False
  4426. probe_pp = False
  4427. try:
  4428. for key in self.cnc_tools:
  4429. ppg = self.cnc_tools[key]['data']['ppname_g']
  4430. if ppg == 'marlin' or ppg == 'Repetier':
  4431. marlin = True
  4432. break
  4433. if ppg == 'hpgl':
  4434. hpgl = True
  4435. break
  4436. if "toolchange_probe" in ppg.lower():
  4437. probe_pp = True
  4438. break
  4439. except Exception as e:
  4440. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  4441. try:
  4442. if self.options['ppname_e'] == 'marlin' or self.options['ppname_e'] == 'Repetier':
  4443. marlin = True
  4444. except Exception as e:
  4445. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4446. try:
  4447. if "toolchange_probe" in self.options['ppname_e'].lower():
  4448. probe_pp = True
  4449. except Exception as e:
  4450. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4451. if marlin is True:
  4452. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4453. (str(self.app.version), str(self.app.version_date)) + '\n'
  4454. gcode += ';Name: ' + str(self.options['name']) + '\n'
  4455. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  4456. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4457. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4458. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  4459. gcode += ';Created on ' + time_str + '\n' + '\n'
  4460. elif hpgl is True:
  4461. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  4462. (str(self.app.version), str(self.app.version_date)) + '";\n'
  4463. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  4464. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  4465. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4466. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4467. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  4468. gcode += 'CO "Created on ' + time_str + '";\n'
  4469. elif probe_pp is True:
  4470. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4471. (str(self.app.version), str(self.app.version_date)) + '\n'
  4472. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  4473. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  4474. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  4475. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  4476. 'Then zero the Z axis.)\n' + '\n'
  4477. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4478. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4479. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4480. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4481. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4482. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4483. else:
  4484. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4485. (str(self.app.version), str(self.app.version_date)) + '\n'
  4486. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4487. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4488. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4489. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4490. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4491. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4492. return gcode
  4493. def gcode_footer(self, end_command=None):
  4494. """
  4495. :param end_command: 'M02' or 'M30' - String
  4496. :return:
  4497. """
  4498. if end_command:
  4499. return end_command
  4500. else:
  4501. return 'M02'
  4502. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  4503. gcode = ''
  4504. roland = False
  4505. hpgl = False
  4506. try:
  4507. if self.special_group:
  4508. self.app.inform.emit(_("[WARNING_NOTCL] This CNCJob object can't be processed because "
  4509. "it is a %s CNCJob object.") % str(self.special_group))
  4510. return 'fail'
  4511. except AttributeError:
  4512. pass
  4513. # detect if using Roland postprocessor
  4514. try:
  4515. for key in self.cnc_tools:
  4516. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  4517. roland = True
  4518. break
  4519. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  4520. hpgl = True
  4521. break
  4522. except:
  4523. try:
  4524. for key in self.cnc_tools:
  4525. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  4526. roland = True
  4527. break
  4528. except:
  4529. pass
  4530. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  4531. if roland is False and hpgl is False:
  4532. gcode = self.gcode_header()
  4533. # detect if using multi-tool and make the Gcode summation correctly for each case
  4534. if self.multitool is True:
  4535. for tooluid_key in self.cnc_tools:
  4536. for key, value in self.cnc_tools[tooluid_key].items():
  4537. if key == 'gcode':
  4538. gcode += value
  4539. break
  4540. else:
  4541. gcode += self.gcode
  4542. if roland is True:
  4543. g = preamble + gcode + postamble
  4544. elif hpgl is True:
  4545. g = self.gcode_header() + preamble + gcode + postamble
  4546. else:
  4547. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  4548. g_idx = gcode.rfind('G20')
  4549. # if it did not find 'G20' then search for 'G21'
  4550. if g_idx == -1:
  4551. g_idx = gcode.rfind('G21')
  4552. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  4553. if g_idx == -1:
  4554. self.app.inform.emit(_(
  4555. "[ERROR_NOTCL] G-code does not have a units code: either G20 or G21"
  4556. ))
  4557. return
  4558. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble + self.gcode_footer()
  4559. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  4560. if self.ui.toolchange_cb.get_value() is True:
  4561. # match = self.re_toolchange.search(g)
  4562. if 'M6' in g:
  4563. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  4564. if m6_code is None or m6_code == '':
  4565. self.app.inform.emit(_(
  4566. "[ERROR_NOTCL] Cancelled. The Toolchange Custom code is enabled "
  4567. "but it's empty."
  4568. ))
  4569. return 'fail'
  4570. g = g.replace('M6', m6_code)
  4571. self.app.inform.emit(_(
  4572. "[success] Toolchange G-code was replaced by a custom code."
  4573. ))
  4574. # lines = StringIO(self.gcode)
  4575. lines = StringIO(g)
  4576. ## Write
  4577. if filename is not None:
  4578. try:
  4579. with open(filename, 'w') as f:
  4580. for line in lines:
  4581. f.write(line)
  4582. except FileNotFoundError:
  4583. self.app.inform.emit(_(
  4584. "[WARNING_NOTCL] No such file or directory"
  4585. ))
  4586. return
  4587. elif to_file is False:
  4588. # Just for adding it to the recent files list.
  4589. self.app.file_opened.emit("cncjob", filename)
  4590. self.app.file_saved.emit("cncjob", filename)
  4591. self.app.inform.emit("[success] Saved to: " + filename)
  4592. else:
  4593. return lines
  4594. def on_toolchange_custom_clicked(self, signal):
  4595. try:
  4596. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  4597. if self.ui.toolchange_cb.get_value():
  4598. self.ui.toolchange_cb.set_value(False)
  4599. self.app.inform.emit(
  4600. _(
  4601. "[WARNING_NOTCL] The used postprocessor file has to have in it's name: 'toolchange_custom'"
  4602. ))
  4603. except KeyError:
  4604. try:
  4605. for key in self.cnc_tools:
  4606. ppg = self.cnc_tools[key]['data']['ppname_g']
  4607. if 'toolchange_custom' not in str(ppg).lower():
  4608. print(ppg)
  4609. if self.ui.toolchange_cb.get_value():
  4610. self.ui.toolchange_cb.set_value(False)
  4611. self.app.inform.emit(
  4612. _(
  4613. "[WARNING_NOTCL] The used postprocessor file has to have in it's name: "
  4614. "'toolchange_custom'"
  4615. ))
  4616. except KeyError:
  4617. self.app.inform.emit(
  4618. _(
  4619. "[ERROR] There is no postprocessor file."
  4620. ))
  4621. def get_gcode(self, preamble='', postamble=''):
  4622. #we need this to be able get_gcode separatelly for shell command export_gcode
  4623. return preamble + '\n' + self.gcode + "\n" + postamble
  4624. def get_svg(self):
  4625. # we need this to be able get_svg separately for shell command export_svg
  4626. pass
  4627. def on_plot_cb_click(self, *args):
  4628. if self.muted_ui:
  4629. return
  4630. kind = self.ui.cncplot_method_combo.get_value()
  4631. self.plot(kind=kind)
  4632. self.read_form_item('plot')
  4633. self.ui_disconnect()
  4634. cb_flag = self.ui.plot_cb.isChecked()
  4635. for row in range(self.ui.cnc_tools_table.rowCount()):
  4636. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  4637. if cb_flag:
  4638. table_cb.setChecked(True)
  4639. else:
  4640. table_cb.setChecked(False)
  4641. self.ui_connect()
  4642. def on_plot_cb_click_table(self):
  4643. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4644. self.ui_disconnect()
  4645. cw = self.sender()
  4646. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  4647. cw_row = cw_index.row()
  4648. kind = self.ui.cncplot_method_combo.get_value()
  4649. self.shapes.clear(update=True)
  4650. for tooluid_key in self.cnc_tools:
  4651. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4652. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4653. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  4654. for r in range(self.ui.cnc_tools_table.rowCount()):
  4655. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  4656. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  4657. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  4658. self.shapes.redraw()
  4659. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4660. # if all the row plot's are enabled also enable the general plot checkbox
  4661. cb_cnt = 0
  4662. total_row = self.ui.cnc_tools_table.rowCount()
  4663. for row in range(total_row):
  4664. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  4665. cb_cnt += 1
  4666. else:
  4667. cb_cnt -= 1
  4668. if cb_cnt < total_row:
  4669. self.ui.plot_cb.setChecked(False)
  4670. else:
  4671. self.ui.plot_cb.setChecked(True)
  4672. self.ui_connect()
  4673. def plot(self, visible=None, kind='all'):
  4674. # Does all the required setup and returns False
  4675. # if the 'ptint' option is set to False.
  4676. if not FlatCAMObj.plot(self):
  4677. return
  4678. visible = visible if visible else self.options['plot']
  4679. try:
  4680. if self.multitool is False: # single tool usage
  4681. self.plot2(tooldia=float(self.options["tooldia"]), obj=self, visible=visible, kind=kind)
  4682. else:
  4683. # multiple tools usage
  4684. for tooluid_key in self.cnc_tools:
  4685. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4686. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4687. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  4688. self.shapes.redraw()
  4689. except (ObjectDeleted, AttributeError):
  4690. self.shapes.clear(update=True)
  4691. self.annotation.clear(update=True)
  4692. def convert_units(self, units):
  4693. factor = CNCjob.convert_units(self, units)
  4694. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  4695. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  4696. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4697. 'endz', 'toolchangez']
  4698. temp_tools_dict = {}
  4699. tool_dia_copy = {}
  4700. data_copy = {}
  4701. for tooluid_key, tooluid_value in self.cnc_tools.items():
  4702. for dia_key, dia_value in tooluid_value.items():
  4703. if dia_key == 'tooldia':
  4704. dia_value *= factor
  4705. dia_value = float('%.4f' % dia_value)
  4706. tool_dia_copy[dia_key] = dia_value
  4707. if dia_key == 'offset':
  4708. tool_dia_copy[dia_key] = dia_value
  4709. if dia_key == 'offset_value':
  4710. dia_value *= factor
  4711. tool_dia_copy[dia_key] = dia_value
  4712. if dia_key == 'type':
  4713. tool_dia_copy[dia_key] = dia_value
  4714. if dia_key == 'tool_type':
  4715. tool_dia_copy[dia_key] = dia_value
  4716. if dia_key == 'data':
  4717. for data_key, data_value in dia_value.items():
  4718. # convert the form fields that are convertible
  4719. for param in param_list:
  4720. if data_key == param and data_value is not None:
  4721. data_copy[data_key] = data_value * factor
  4722. # copy the other dict entries that are not convertible
  4723. if data_key not in param_list:
  4724. data_copy[data_key] = data_value
  4725. tool_dia_copy[dia_key] = deepcopy(data_copy)
  4726. data_copy.clear()
  4727. if dia_key == 'gcode':
  4728. tool_dia_copy[dia_key] = dia_value
  4729. if dia_key == 'gcode_parsed':
  4730. tool_dia_copy[dia_key] = dia_value
  4731. if dia_key == 'solid_geometry':
  4732. tool_dia_copy[dia_key] = dia_value
  4733. # if dia_key == 'solid_geometry':
  4734. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  4735. # if dia_key == 'gcode_parsed':
  4736. # for g in dia_value:
  4737. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  4738. #
  4739. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  4740. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  4741. temp_tools_dict.update({
  4742. tooluid_key: deepcopy(tool_dia_copy)
  4743. })
  4744. tool_dia_copy.clear()
  4745. self.cnc_tools.clear()
  4746. self.cnc_tools = deepcopy(temp_tools_dict)
  4747. # end of file