FlatCAMObj.py 252 KB

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