FlatCAMObj.py 327 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597
  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. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from shapely.geometry import Point, Polygon, MultiPolygon, MultiLineString, LineString, LinearRing
  12. from shapely.ops import cascaded_union
  13. import shapely.affinity as affinity
  14. from copy import deepcopy
  15. from copy import copy
  16. from io import StringIO
  17. import traceback
  18. import inspect # TODO: For debugging only.
  19. from datetime import datetime
  20. from flatcamEditors.FlatCAMTextEditor import TextEditor
  21. from flatcamGUI.ObjectUI import *
  22. from FlatCAMCommon import LoudDict
  23. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  24. from flatcamParsers.ParseExcellon import Excellon
  25. from flatcamParsers.ParseGerber import Gerber
  26. from camlib import Geometry, CNCjob
  27. import FlatCAMApp
  28. from flatcamGUI.VisPyVisuals import ShapeCollection
  29. import tkinter as tk
  30. import os, sys, itertools
  31. import ezdxf
  32. import math
  33. import numpy as np
  34. import gettext
  35. import FlatCAMTranslation as fcTranslate
  36. import builtins
  37. fcTranslate.apply_language('strings')
  38. if '_' not in builtins.__dict__:
  39. _ = gettext.gettext
  40. # Interrupts plotting process if FlatCAMObj has been deleted
  41. class ObjectDeleted(Exception):
  42. pass
  43. class ValidationError(Exception):
  44. def __init__(self, message, errors):
  45. super().__init__(message)
  46. self.errors = errors
  47. # #######################################
  48. # # FlatCAMObj ##
  49. # #######################################
  50. class FlatCAMObj(QtCore.QObject):
  51. """
  52. Base type of objects handled in FlatCAM. These become interactive
  53. in the GUI, can be plotted, and their options can be modified
  54. by the user in their respective forms.
  55. """
  56. # Instance of the application to which these are related.
  57. # The app should set this value.
  58. app = None
  59. # signal to plot a single object
  60. plot_single_object = QtCore.pyqtSignal()
  61. def __init__(self, name):
  62. """
  63. Constructor.
  64. :param name: Name of the object given by the user.
  65. :return: FlatCAMObj
  66. """
  67. QtCore.QObject.__init__(self)
  68. # View
  69. self.ui = None
  70. self.options = LoudDict(name=name)
  71. self.options.set_change_callback(self.on_options_change)
  72. self.form_fields = {}
  73. # store here the default data for Geometry Data
  74. self.default_data = {}
  75. # 2D mode
  76. # Axes must exist and be attached to canvas.
  77. self.axes = None
  78. self.kind = None # Override with proper name
  79. if self.app.is_legacy is False:
  80. self.shapes = self.app.plotcanvas.new_shape_group()
  81. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, pool=self.app.pool, layers=2)
  82. else:
  83. self.shapes = ShapeCollectionLegacy(obj=self, app=self.app, name=name)
  84. self.mark_shapes = dict()
  85. self.item = None # Link with project view item
  86. self.muted_ui = False
  87. self.deleted = False
  88. try:
  89. self._drawing_tolerance = float(self.app.defaults["global_tolerance"]) if \
  90. self.app.defaults["global_tolerance"] else 0.01
  91. except ValueError:
  92. self._drawing_tolerance = 0.01
  93. self.isHovering = False
  94. self.notHovering = True
  95. # Flag to show if a selection shape is drawn
  96. self.selection_shape_drawn = False
  97. # self.units = 'IN'
  98. self.units = self.app.defaults['units']
  99. self.plot_single_object.connect(self.single_object_plot)
  100. def __del__(self):
  101. pass
  102. def __str__(self):
  103. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  104. def from_dict(self, d):
  105. """
  106. This supersedes ``from_dict`` in derived classes. Derived classes
  107. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  108. ``self.options`` is only updated, not overwritten. This ensures that
  109. options set by the app do not vanish when reading the objects
  110. from a project file.
  111. :param d: Dictionary with attributes to set.
  112. :return: None
  113. """
  114. for attr in self.ser_attrs:
  115. if attr == 'options':
  116. self.options.update(d[attr])
  117. else:
  118. try:
  119. setattr(self, attr, d[attr])
  120. except KeyError:
  121. log.debug("FlatCAMObj.from_dict() --> KeyError: %s. "
  122. "Means that we are loading an old project that don't"
  123. "have all attributes in the latest FlatCAM." % str(attr))
  124. pass
  125. def on_options_change(self, key):
  126. # Update form on programmatically options change
  127. self.set_form_item(key)
  128. # Set object visibility
  129. if key == 'plot':
  130. self.visible = self.options['plot']
  131. self.optionChanged.emit(key)
  132. def set_ui(self, ui):
  133. self.ui = ui
  134. self.form_fields = {"name": self.ui.name_entry}
  135. assert isinstance(self.ui, ObjectUI)
  136. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  137. try:
  138. # it will raise an exception for those FlatCAM objects that do not build UI with the common elements
  139. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  140. except (TypeError, AttributeError):
  141. pass
  142. try:
  143. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  144. except (TypeError, AttributeError):
  145. pass
  146. try:
  147. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  148. except (TypeError, AttributeError):
  149. pass
  150. # Creates problems on focusOut
  151. try:
  152. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  153. except (TypeError, AttributeError):
  154. pass
  155. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  156. def build_ui(self):
  157. """
  158. Sets up the UI/form for this object. Show the UI
  159. in the App.
  160. :return: None
  161. :rtype: None
  162. """
  163. self.muted_ui = True
  164. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  165. try:
  166. # HACK: disconnect the scale entry signal since on focus out event will trigger an undesired scale()
  167. # it seems that the takewidget() does generate a focus out event for the QDoubleSpinbox ...
  168. # and reconnect after the takeWidget() is done
  169. # self.ui.scale_entry.returnPressed.disconnect(self.on_scale_button_click)
  170. self.app.ui.selected_scroll_area.takeWidget()
  171. # self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  172. except Exception as e:
  173. self.app.log.debug("FlatCAMObj.build_ui() --> Nothing to remove: %s" % str(e))
  174. self.app.ui.selected_scroll_area.setWidget(self.ui)
  175. self.muted_ui = False
  176. def on_name_activate(self, silent=None):
  177. old_name = copy(self.options["name"])
  178. new_name = self.ui.name_entry.get_value()
  179. if new_name != old_name:
  180. # update the SHELL auto-completer model data
  181. try:
  182. self.app.myKeywords.remove(old_name)
  183. self.app.myKeywords.append(new_name)
  184. self.app.shell._edit.set_model_data(self.app.myKeywords)
  185. self.app.ui.code_editor.set_model_data(self.app.myKeywords)
  186. except Exception as e:
  187. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  188. self.options["name"] = self.ui.name_entry.get_value()
  189. self.default_data["name"] = self.ui.name_entry.get_value()
  190. self.app.collection.update_view()
  191. if silent:
  192. self.app.inform.emit('[success] %s: %s %s: %s' % (
  193. _("Name changed from"), str(old_name), _("to"), str(new_name)
  194. )
  195. )
  196. def on_offset_button_click(self):
  197. self.app.report_usage("obj_on_offset_button")
  198. self.read_form()
  199. vector_val = self.ui.offsetvector_entry.get_value()
  200. def worker_task():
  201. with self.app.proc_container.new(_("Offsetting...")):
  202. self.offset(vector_val)
  203. self.app.proc_container.update_view_text('')
  204. with self.app.proc_container.new('%s...' % _("Plotting")):
  205. self.plot()
  206. self.app.object_changed.emit(self)
  207. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  208. def on_scale_button_click(self):
  209. self.read_form()
  210. try:
  211. factor = float(eval(self.ui.scale_entry.get_value()))
  212. except Exception as e:
  213. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scaling could not be executed."))
  214. log.debug("FlatCAMObj.on_scale_button_click() -- %s" % str(e))
  215. return
  216. if type(factor) != float:
  217. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scaling could not be executed."))
  218. # if factor is 1.0 do nothing, there is no point in scaling with a factor of 1.0
  219. if factor == 1.0:
  220. self.app.inform.emit('[success] %s' % _("Scale done."))
  221. return
  222. log.debug("FlatCAMObj.on_scale_button_click()")
  223. def worker_task():
  224. with self.app.proc_container.new(_("Scaling...")):
  225. self.scale(factor)
  226. self.app.inform.emit('[success] %s' % _("Scale done."))
  227. self.app.proc_container.update_view_text('')
  228. with self.app.proc_container.new('%s...' % _("Plotting")):
  229. self.plot()
  230. self.app.object_changed.emit(self)
  231. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  232. def on_skew_button_click(self):
  233. self.app.report_usage("obj_on_skew_button")
  234. self.read_form()
  235. x_angle = self.ui.xangle_entry.get_value()
  236. y_angle = self.ui.yangle_entry.get_value()
  237. def worker_task():
  238. with self.app.proc_container.new(_("Skewing...")):
  239. self.skew(x_angle, y_angle)
  240. self.app.proc_container.update_view_text('')
  241. with self.app.proc_container.new('%s...' % _("Plotting")):
  242. self.plot()
  243. self.app.object_changed.emit(self)
  244. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  245. def to_form(self):
  246. """
  247. Copies options to the UI form.
  248. :return: None
  249. """
  250. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  251. for option in self.options:
  252. try:
  253. self.set_form_item(option)
  254. except Exception:
  255. self.app.log.warning("Unexpected error:", sys.exc_info())
  256. def read_form(self):
  257. """
  258. Reads form into ``self.options``.
  259. :return: None
  260. :rtype: None
  261. """
  262. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  263. for option in self.options:
  264. try:
  265. self.read_form_item(option)
  266. except Exception:
  267. self.app.log.warning("Unexpected error:", sys.exc_info())
  268. def set_form_item(self, option):
  269. """
  270. Copies the specified option to the UI form.
  271. :param option: Name of the option (Key in ``self.options``).
  272. :type option: str
  273. :return: None
  274. """
  275. try:
  276. self.form_fields[option].set_value(self.options[option])
  277. except KeyError:
  278. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  279. pass
  280. def read_form_item(self, option):
  281. """
  282. Reads the specified option from the UI form into ``self.options``.
  283. :param option: Name of the option.
  284. :type option: str
  285. :return: None
  286. """
  287. try:
  288. self.options[option] = self.form_fields[option].get_value()
  289. except KeyError:
  290. pass
  291. # self.app.log.warning("Failed to read option from field: %s" % option)
  292. def plot(self):
  293. """
  294. Plot this object (Extend this method to implement the actual plotting).
  295. Call this in descendants before doing the plotting.
  296. :return: Whether to continue plotting or not depending on the "plot" option.
  297. :rtype: bool
  298. """
  299. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  300. if self.deleted:
  301. return False
  302. self.clear()
  303. return True
  304. def single_object_plot(self):
  305. def plot_task():
  306. with self.app.proc_container.new('%s...' % _("Plotting")):
  307. self.plot()
  308. self.app.object_changed.emit(self)
  309. self.app.worker_task.emit({'fcn': plot_task, 'params': []})
  310. def serialize(self):
  311. """
  312. Returns a representation of the object as a dictionary so
  313. it can be later exported as JSON. Override this method.
  314. :return: Dictionary representing the object
  315. :rtype: dict
  316. """
  317. return
  318. def deserialize(self, obj_dict):
  319. """
  320. Re-builds an object from its serialized version.
  321. :param obj_dict: Dictionary representing a FlatCAMObj
  322. :type obj_dict: dict
  323. :return: None
  324. """
  325. return
  326. def add_shape(self, **kwargs):
  327. if self.deleted:
  328. raise ObjectDeleted()
  329. else:
  330. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  331. return key
  332. def add_mark_shape(self, apid, **kwargs):
  333. if self.deleted:
  334. raise ObjectDeleted()
  335. else:
  336. key = self.mark_shapes[apid].add(tolerance=self.drawing_tolerance, layer=0, **kwargs)
  337. return key
  338. def update_filters(self, last_ext, filter_string):
  339. """
  340. Will modify the filter string that is used when saving a file (a list of file extensions) to have the last
  341. used file extension as the first one in the special string
  342. :param last_ext: the file extension that was last used to save a file
  343. :param filter_string: a key in self.app.defaults that holds a string with the filter from QFileDialog
  344. used when saving a file
  345. :return: None
  346. """
  347. filters = copy(self.app.defaults[filter_string])
  348. filter_list = filters.split(';;')
  349. filter_list_enum_1 = enumerate(filter_list)
  350. # search for the last element in the filters which should always be "All Files (*.*)"
  351. last_elem = ''
  352. for elem in list(filter_list_enum_1):
  353. if '(*.*)' in elem[1]:
  354. last_elem = filter_list.pop(elem[0])
  355. filter_list_enum = enumerate(filter_list)
  356. for elem in list(filter_list_enum):
  357. if '.' + last_ext in elem[1]:
  358. used_ext = filter_list.pop(elem[0])
  359. # sort the extensions back
  360. filter_list.sort(key=lambda x: x.rpartition('.')[2])
  361. # add as a first element the last used extension
  362. filter_list.insert(0, used_ext)
  363. # add back the element that should always be the last (All Files)
  364. filter_list.append(last_elem)
  365. self.app.defaults[filter_string] = ';;'.join(filter_list)
  366. return
  367. @staticmethod
  368. def poly2rings(poly):
  369. return [poly.exterior] + [interior for interior in poly.interiors]
  370. @property
  371. def visible(self):
  372. return self.shapes.visible
  373. @visible.setter
  374. def visible(self, value, threaded=True):
  375. log.debug("FlatCAMObj.visible()")
  376. def worker_task(app_obj):
  377. self.shapes.visible = value
  378. if self.app.is_legacy is False:
  379. # Not all object types has annotations
  380. try:
  381. self.annotation.visible = value
  382. except Exception as e:
  383. pass
  384. if threaded is False:
  385. worker_task(app_obj=self.app)
  386. else:
  387. self.app.worker_task.emit({'fcn': worker_task, 'params': [self]})
  388. @property
  389. def drawing_tolerance(self):
  390. self.units = self.app.defaults['units'].upper()
  391. tol = self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  392. return tol
  393. @drawing_tolerance.setter
  394. def drawing_tolerance(self, value):
  395. self.units = self.app.defaults['units'].upper()
  396. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  397. def clear(self, update=False):
  398. self.shapes.clear(update)
  399. # Not all object types has annotations
  400. try:
  401. self.annotation.clear(update)
  402. except AttributeError:
  403. pass
  404. def delete(self):
  405. # Free resources
  406. del self.ui
  407. del self.options
  408. # Set flag
  409. self.deleted = True
  410. class FlatCAMGerber(FlatCAMObj, Gerber):
  411. """
  412. Represents Gerber code.
  413. """
  414. optionChanged = QtCore.pyqtSignal(str)
  415. replotApertures = QtCore.pyqtSignal()
  416. ui_type = GerberObjectUI
  417. def merge(self, grb_list, grb_final):
  418. """
  419. Merges the geometry of objects in geo_list into
  420. the geometry of geo_final.
  421. :param grb_list: List of FlatCAMGerber Objects to join.
  422. :param grb_final: Destination FlatCAMGeometry object.
  423. :return: None
  424. """
  425. if grb_final.solid_geometry is None:
  426. grb_final.solid_geometry = []
  427. grb_final.follow_geometry = []
  428. if not grb_final.apertures:
  429. grb_final.apertures = {}
  430. if type(grb_final.solid_geometry) is not list:
  431. grb_final.solid_geometry = [grb_final.solid_geometry]
  432. grb_final.follow_geometry = [grb_final.follow_geometry]
  433. for grb in grb_list:
  434. # Expand lists
  435. if type(grb) is list:
  436. FlatCAMGerber.merge(grb, grb_final)
  437. else: # If not list, just append
  438. for option in grb.options:
  439. if option is not 'name':
  440. try:
  441. grb_final.options[option] = grb.options[option]
  442. except KeyError:
  443. log.warning("Failed to copy option.", option)
  444. try:
  445. for geos in grb.solid_geometry:
  446. grb_final.solid_geometry.append(geos)
  447. grb_final.follow_geometry.append(geos)
  448. except TypeError:
  449. grb_final.solid_geometry.append(grb.solid_geometry)
  450. grb_final.follow_geometry.append(grb.solid_geometry)
  451. for ap in grb.apertures:
  452. if ap not in grb_final.apertures:
  453. grb_final.apertures[ap] = grb.apertures[ap]
  454. else:
  455. # create a list of integers out of the grb.apertures keys and find the max of that value
  456. # then, the aperture duplicate is assigned an id value incremented with 1,
  457. # and finally made string because the apertures dict keys are strings
  458. max_ap = str(max([int(k) for k in grb_final.apertures.keys()]) + 1)
  459. grb_final.apertures[max_ap] = {}
  460. grb_final.apertures[max_ap]['geometry'] = []
  461. for k, v in grb.apertures[ap].items():
  462. grb_final.apertures[max_ap][k] = deepcopy(v)
  463. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  464. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  465. def __init__(self, name):
  466. self.decimals = self.app.decimals
  467. self.circle_steps = int(self.app.defaults["gerber_circle_steps"])
  468. Gerber.__init__(self, steps_per_circle=self.circle_steps)
  469. FlatCAMObj.__init__(self, name)
  470. self.kind = "gerber"
  471. # The 'name' is already in self.options from FlatCAMObj
  472. # Automatically updates the UI
  473. self.options.update({
  474. "plot": True,
  475. "multicolored": False,
  476. "solid": False,
  477. "tool_type": 'circular',
  478. "vtipdia": 0.1,
  479. "vtipangle": 30,
  480. "vcutz": -0.05,
  481. "isotooldia": 0.016,
  482. "isopasses": 1,
  483. "isooverlap": 15,
  484. "milling_type": "cl",
  485. "combine_passes": True,
  486. "noncoppermargin": 0.0,
  487. "noncopperrounded": False,
  488. "bboxmargin": 0.0,
  489. "bboxrounded": False,
  490. "aperture_display": False,
  491. "follow": False,
  492. "iso_scope": 'all',
  493. "iso_type": 'full'
  494. })
  495. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  496. self.iso_type = 2
  497. self.multigeo = False
  498. self.follow = False
  499. self.apertures_row = 0
  500. # store the source file here
  501. self.source_file = ""
  502. # list of rows with apertures plotted
  503. self.marked_rows = []
  504. # Mouse events
  505. self.mr = None
  506. self.mm = None
  507. self.mp = None
  508. # dict to store the polygons selected for isolation; key is the shape added to be plotted and value is the poly
  509. self.poly_dict = dict()
  510. # store the status of grid snapping
  511. self.grid_status_memory = None
  512. self.units_found = self.app.defaults['units']
  513. self.fill_color = self.app.defaults['global_plot_fill']
  514. self.outline_color = self.app.defaults['global_plot_line']
  515. # Attributes to be included in serialization
  516. # Always append to it because it carries contents
  517. # from predecessors.
  518. self.ser_attrs += ['options', 'kind', 'fill_color', 'outline_color']
  519. def set_ui(self, ui):
  520. """
  521. Maps options with GUI inputs.
  522. Connects GUI events to methods.
  523. :param ui: GUI object.
  524. :type ui: GerberObjectUI
  525. :return: None
  526. """
  527. FlatCAMObj.set_ui(self, ui)
  528. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  529. self.units = self.app.defaults['units'].upper()
  530. self.replotApertures.connect(self.on_mark_cb_click_table)
  531. self.form_fields.update({
  532. "plot": self.ui.plot_cb,
  533. "multicolored": self.ui.multicolored_cb,
  534. "solid": self.ui.solid_cb,
  535. "tool_type": self.ui.tool_type_radio,
  536. "vtipdia": self.ui.tipdia_spinner,
  537. "vtipangle": self.ui.tipangle_spinner,
  538. "vcutz": self.ui.cutz_spinner,
  539. "isotooldia": self.ui.iso_tool_dia_entry,
  540. "isopasses": self.ui.iso_width_entry,
  541. "isooverlap": self.ui.iso_overlap_entry,
  542. "milling_type": self.ui.milling_type_radio,
  543. "combine_passes": self.ui.combine_passes_cb,
  544. "noncoppermargin": self.ui.noncopper_margin_entry,
  545. "noncopperrounded": self.ui.noncopper_rounded_cb,
  546. "bboxmargin": self.ui.bbmargin_entry,
  547. "bboxrounded": self.ui.bbrounded_cb,
  548. "aperture_display": self.ui.aperture_table_visibility_cb,
  549. "follow": self.ui.follow_cb,
  550. "iso_scope": self.ui.iso_scope_radio,
  551. "iso_type": self.ui.iso_type_radio
  552. })
  553. # Fill form fields only on object create
  554. self.to_form()
  555. assert isinstance(self.ui, GerberObjectUI)
  556. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  557. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  558. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  559. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  560. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  561. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  562. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  563. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  564. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  565. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  566. # set the model for the Area Exception comboboxes
  567. self.ui.obj_combo.setModel(self.app.collection)
  568. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  569. self.ui.obj_combo.setCurrentIndex(1)
  570. self.ui.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  571. self.ui.tool_type_radio.activated_custom.connect(self.on_tool_type_change)
  572. # establish visibility for the GUI elements found in the slot function
  573. self.ui.tool_type_radio.activated_custom.emit(self.options['tool_type'])
  574. # Show/Hide Advanced Options
  575. if self.app.defaults["global_app_level"] == 'b':
  576. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  577. self.options['tool_type'] = 'circular'
  578. self.ui.tool_type_label.hide()
  579. self.ui.tool_type_radio.hide()
  580. self.ui.tipdialabel.hide()
  581. self.ui.tipdia_spinner.hide()
  582. self.ui.tipanglelabel.hide()
  583. self.ui.tipangle_spinner.hide()
  584. self.ui.cutzlabel.hide()
  585. self.ui.cutz_spinner.hide()
  586. self.ui.apertures_table_label.hide()
  587. self.ui.aperture_table_visibility_cb.hide()
  588. self.ui.milling_type_label.hide()
  589. self.ui.milling_type_radio.hide()
  590. self.ui.iso_type_label.hide()
  591. self.ui.iso_type_radio.hide()
  592. self.ui.follow_cb.hide()
  593. self.ui.except_cb.setChecked(False)
  594. self.ui.except_cb.hide()
  595. else:
  596. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  597. self.ui.tipdia_spinner.valueChanged.connect(self.on_calculate_tooldia)
  598. self.ui.tipangle_spinner.valueChanged.connect(self.on_calculate_tooldia)
  599. self.ui.cutz_spinner.valueChanged.connect(self.on_calculate_tooldia)
  600. if self.app.defaults["gerber_buffering"] == 'no':
  601. self.ui.create_buffer_button.show()
  602. try:
  603. self.ui.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  604. except TypeError:
  605. pass
  606. self.ui.create_buffer_button.clicked.connect(self.on_generate_buffer)
  607. else:
  608. self.ui.create_buffer_button.hide()
  609. # set initial state of the aperture table and associated widgets
  610. self.on_aperture_table_visibility_change()
  611. self.build_ui()
  612. self.units_found = self.app.defaults['units']
  613. def on_calculate_tooldia(self):
  614. try:
  615. tdia = float(self.ui.tipdia_spinner.get_value())
  616. except Exception as e:
  617. return
  618. try:
  619. dang = float(self.ui.tipangle_spinner.get_value())
  620. except Exception as e:
  621. return
  622. try:
  623. cutz = float(self.ui.cutz_spinner.get_value())
  624. except Exception as e:
  625. return
  626. cutz *= -1
  627. if cutz < 0:
  628. cutz *= -1
  629. half_tip_angle = dang / 2
  630. tool_diameter = tdia + (2 * cutz * math.tan(math.radians(half_tip_angle)))
  631. self.ui.iso_tool_dia_entry.set_value(tool_diameter)
  632. def on_type_obj_index_changed(self, index):
  633. obj_type = self.ui.type_obj_combo.currentIndex()
  634. self.ui.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  635. self.ui.obj_combo.setCurrentIndex(0)
  636. def on_tool_type_change(self, state):
  637. if state == 'circular':
  638. self.ui.tipdialabel.hide()
  639. self.ui.tipdia_spinner.hide()
  640. self.ui.tipanglelabel.hide()
  641. self.ui.tipangle_spinner.hide()
  642. self.ui.cutzlabel.hide()
  643. self.ui.cutz_spinner.hide()
  644. self.ui.iso_tool_dia_entry.setDisabled(False)
  645. # update the value in the self.iso_tool_dia_entry once this is selected
  646. self.ui.iso_tool_dia_entry.set_value(self.options['isotooldia'])
  647. else:
  648. self.ui.tipdialabel.show()
  649. self.ui.tipdia_spinner.show()
  650. self.ui.tipanglelabel.show()
  651. self.ui.tipangle_spinner.show()
  652. self.ui.cutzlabel.show()
  653. self.ui.cutz_spinner.show()
  654. self.ui.iso_tool_dia_entry.setDisabled(True)
  655. # update the value in the self.iso_tool_dia_entry once this is selected
  656. self.on_calculate_tooldia()
  657. def build_ui(self):
  658. FlatCAMObj.build_ui(self)
  659. try:
  660. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  661. self.ui.apertures_table.itemChanged.disconnect()
  662. except (TypeError, AttributeError):
  663. pass
  664. self.apertures_row = 0
  665. aper_no = self.apertures_row + 1
  666. sort = []
  667. for k, v in list(self.apertures.items()):
  668. sort.append(int(k))
  669. sorted_apertures = sorted(sort)
  670. # sort = []
  671. # for k, v in list(self.aperture_macros.items()):
  672. # sort.append(k)
  673. # sorted_macros = sorted(sort)
  674. # n = len(sorted_apertures) + len(sorted_macros)
  675. n = len(sorted_apertures)
  676. self.ui.apertures_table.setRowCount(n)
  677. for ap_code in sorted_apertures:
  678. ap_code = str(ap_code)
  679. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  680. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  681. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  682. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  683. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  684. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  685. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  686. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  687. ap_dim_item = QtWidgets.QTableWidgetItem(
  688. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['width'],
  689. self.decimals, self.apertures[ap_code]['height']
  690. )
  691. )
  692. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  693. elif str(self.apertures[ap_code]['type']) == 'P':
  694. ap_dim_item = QtWidgets.QTableWidgetItem(
  695. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['diam'],
  696. self.decimals, self.apertures[ap_code]['nVertices'])
  697. )
  698. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  699. else:
  700. ap_dim_item = QtWidgets.QTableWidgetItem('')
  701. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  702. try:
  703. if self.apertures[ap_code]['size'] is not None:
  704. ap_size_item = QtWidgets.QTableWidgetItem(
  705. '%.*f' % (self.decimals, float(self.apertures[ap_code]['size'])))
  706. else:
  707. ap_size_item = QtWidgets.QTableWidgetItem('')
  708. except KeyError:
  709. ap_size_item = QtWidgets.QTableWidgetItem('')
  710. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  711. mark_item = FCCheckBox()
  712. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  713. # if self.ui.aperture_table_visibility_cb.isChecked():
  714. # mark_item.setChecked(True)
  715. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  716. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  717. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  718. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  719. empty_plot_item = QtWidgets.QTableWidgetItem('')
  720. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  721. self.ui.apertures_table.setItem(self.apertures_row, 5, empty_plot_item)
  722. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  723. self.apertures_row += 1
  724. self.ui.apertures_table.selectColumn(0)
  725. self.ui.apertures_table.resizeColumnsToContents()
  726. self.ui.apertures_table.resizeRowsToContents()
  727. vertical_header = self.ui.apertures_table.verticalHeader()
  728. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  729. vertical_header.hide()
  730. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  731. horizontal_header = self.ui.apertures_table.horizontalHeader()
  732. horizontal_header.setMinimumSectionSize(10)
  733. horizontal_header.setDefaultSectionSize(70)
  734. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  735. horizontal_header.resizeSection(0, 27)
  736. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  737. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  738. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  739. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  740. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  741. horizontal_header.resizeSection(5, 17)
  742. self.ui.apertures_table.setColumnWidth(5, 17)
  743. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  744. self.ui.apertures_table.setSortingEnabled(False)
  745. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  746. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  747. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  748. if self.marked_rows:
  749. for row in range(self.ui.apertures_table.rowCount()):
  750. try:
  751. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  752. except IndexError:
  753. pass
  754. self.ui_connect()
  755. def ui_connect(self):
  756. for row in range(self.ui.apertures_table.rowCount()):
  757. try:
  758. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect(self.on_mark_cb_click_table)
  759. except (TypeError, AttributeError):
  760. pass
  761. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  762. try:
  763. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  764. except (TypeError, AttributeError):
  765. pass
  766. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  767. def ui_disconnect(self):
  768. for row in range(self.ui.apertures_table.rowCount()):
  769. try:
  770. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  771. except (TypeError, AttributeError):
  772. pass
  773. try:
  774. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  775. except (TypeError, AttributeError):
  776. pass
  777. def on_generate_buffer(self):
  778. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  779. def buffer_task():
  780. with self.app.proc_container.new('%s...' % _("Buffering")):
  781. if isinstance(self.solid_geometry, list):
  782. self.solid_geometry = MultiPolygon(self.solid_geometry)
  783. self.solid_geometry = self.solid_geometry.buffer(0.0000001)
  784. self.solid_geometry = self.solid_geometry.buffer(-0.0000001)
  785. self.app.inform.emit('[success] %s.' % _("Done"))
  786. self.plot_single_object.emit()
  787. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  788. def on_generatenoncopper_button_click(self, *args):
  789. self.app.report_usage("gerber_on_generatenoncopper_button")
  790. self.read_form()
  791. name = self.options["name"] + "_noncopper"
  792. def geo_init(geo_obj, app_obj):
  793. assert isinstance(geo_obj, FlatCAMGeometry)
  794. if isinstance(self.solid_geometry, list):
  795. self.solid_geometry = cascaded_union(self.solid_geometry)
  796. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  797. if not self.options["noncopperrounded"]:
  798. bounding_box = bounding_box.envelope
  799. non_copper = bounding_box.difference(self.solid_geometry)
  800. geo_obj.solid_geometry = non_copper
  801. # TODO: Check for None
  802. self.app.new_object("geometry", name, geo_init)
  803. def on_generatebb_button_click(self, *args):
  804. self.app.report_usage("gerber_on_generatebb_button")
  805. self.read_form()
  806. name = self.options["name"] + "_bbox"
  807. def geo_init(geo_obj, app_obj):
  808. assert isinstance(geo_obj, FlatCAMGeometry)
  809. # Bounding box with rounded corners
  810. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  811. if not self.options["bboxrounded"]: # Remove rounded corners
  812. bounding_box = bounding_box.envelope
  813. geo_obj.solid_geometry = bounding_box
  814. self.app.new_object("geometry", name, geo_init)
  815. def on_iso_button_click(self, *args):
  816. obj = self.app.collection.get_active()
  817. self.iso_type = 2
  818. if self.ui.iso_type_radio.get_value() == 'ext':
  819. self.iso_type = 0
  820. if self.ui.iso_type_radio.get_value() == 'int':
  821. self.iso_type = 1
  822. def worker_task(obj, app_obj):
  823. with self.app.proc_container.new(_("Isolating...")):
  824. if self.ui.follow_cb.get_value() is True:
  825. obj.follow_geo()
  826. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  827. obj.ui.plot_cb.toggle()
  828. else:
  829. app_obj.report_usage("gerber_on_iso_button")
  830. self.read_form()
  831. iso_scope = 'all' if self.ui.iso_scope_radio.get_value() == 'all' else 'single'
  832. self.isolate_handler(iso_type=self.iso_type, iso_scope=iso_scope)
  833. self.app.worker_task.emit({'fcn': worker_task, 'params': [obj, self.app]})
  834. def follow_geo(self, outname=None):
  835. """
  836. Creates a geometry object "following" the gerber paths.
  837. :return: None
  838. """
  839. # default_name = self.options["name"] + "_follow"
  840. # follow_name = outname or default_name
  841. if outname is None:
  842. follow_name = self.options["name"] + "_follow"
  843. else:
  844. follow_name = outname
  845. def follow_init(follow_obj, app):
  846. # Propagate options
  847. follow_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  848. follow_obj.solid_geometry = self.follow_geometry
  849. # TODO: Do something if this is None. Offer changing name?
  850. try:
  851. self.app.new_object("geometry", follow_name, follow_init)
  852. except Exception as e:
  853. return "Operation failed: %s" % str(e)
  854. def isolate_handler(self, iso_type, iso_scope):
  855. if iso_scope == 'all':
  856. self.isolate(iso_type=iso_type)
  857. else:
  858. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  859. if self.app.ui.grid_snap_btn.isChecked():
  860. self.grid_status_memory = True
  861. self.app.ui.grid_snap_btn.trigger()
  862. else:
  863. self.grid_status_memory = False
  864. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  865. if self.app.is_legacy is False:
  866. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  867. else:
  868. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  869. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to isolate it."))
  870. def on_mouse_click_release(self, event):
  871. if self.app.is_legacy is False:
  872. event_pos = event.pos
  873. right_button = 2
  874. self.app.event_is_dragging = self.app.event_is_dragging
  875. else:
  876. event_pos = (event.xdata, event.ydata)
  877. right_button = 3
  878. self.app.event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  879. try:
  880. x = float(event_pos[0])
  881. y = float(event_pos[1])
  882. except TypeError:
  883. return
  884. event_pos = (x, y)
  885. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  886. if self.app.grid_status():
  887. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  888. else:
  889. curr_pos = (curr_pos[0], curr_pos[1])
  890. if event.button == 1:
  891. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]))
  892. if self.app.selection_type is not None:
  893. self.selection_area_handler(self.app.pos, curr_pos, self.app.selection_type)
  894. self.app.selection_type = None
  895. elif clicked_poly:
  896. if clicked_poly not in self.poly_dict.values():
  897. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0, shape=clicked_poly,
  898. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  899. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  900. visible=True)
  901. self.poly_dict[shape_id] = clicked_poly
  902. self.app.inform.emit(
  903. '%s: %d. %s' % (_("Added polygon"),
  904. int(len(self.poly_dict)),
  905. _("Click to add next polygon or right click to start isolation."))
  906. )
  907. else:
  908. try:
  909. for k, v in list(self.poly_dict.items()):
  910. if v == clicked_poly:
  911. self.app.tool_shapes.remove(k)
  912. self.poly_dict.pop(k)
  913. break
  914. except TypeError:
  915. return
  916. self.app.inform.emit(
  917. '%s. %s' % (_("Removed polygon"),
  918. _("Click to add/remove next polygon or right click to start isolation."))
  919. )
  920. self.app.tool_shapes.redraw()
  921. else:
  922. self.app.inform.emit(_("No polygon detected under click position."))
  923. elif event.button == right_button and self.app.event_is_dragging is False:
  924. # restore the Grid snapping if it was active before
  925. if self.grid_status_memory is True:
  926. self.app.ui.grid_snap_btn.trigger()
  927. if self.app.is_legacy is False:
  928. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  929. else:
  930. self.app.plotcanvas.graph_event_disconnect(self.mr)
  931. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  932. self.app.on_mouse_click_release_over_plot)
  933. self.app.tool_shapes.clear(update=True)
  934. if self.poly_dict:
  935. poly_list = deepcopy(list(self.poly_dict.values()))
  936. self.isolate(iso_type=self.iso_type, geometry=poly_list)
  937. self.poly_dict.clear()
  938. else:
  939. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  940. def selection_area_handler(self, start_pos, end_pos, sel_type):
  941. """
  942. :param start_pos: mouse position when the selection LMB click was done
  943. :param end_pos: mouse position when the left mouse button is released
  944. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  945. :return:
  946. """
  947. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  948. # delete previous selection shape
  949. self.app.delete_selection_shape()
  950. added_poly_count = 0
  951. try:
  952. for geo in self.solid_geometry:
  953. if geo not in self.poly_dict.values():
  954. if sel_type is True:
  955. if geo.within(poly_selection):
  956. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  957. shape=geo,
  958. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  959. face_color=self.app.defaults[
  960. 'global_sel_draw_color'] + 'AF',
  961. visible=True)
  962. self.poly_dict[shape_id] = geo
  963. added_poly_count += 1
  964. else:
  965. if poly_selection.intersects(geo):
  966. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  967. shape=geo,
  968. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  969. face_color=self.app.defaults[
  970. 'global_sel_draw_color'] + 'AF',
  971. visible=True)
  972. self.poly_dict[shape_id] = geo
  973. added_poly_count += 1
  974. except TypeError:
  975. if self.solid_geometry not in self.poly_dict.values():
  976. if sel_type is True:
  977. if self.solid_geometry.within(poly_selection):
  978. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  979. shape=self.solid_geometry,
  980. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  981. face_color=self.app.defaults[
  982. 'global_sel_draw_color'] + 'AF',
  983. visible=True)
  984. self.poly_dict[shape_id] = self.solid_geometry
  985. added_poly_count += 1
  986. else:
  987. if poly_selection.intersects(self.solid_geometry):
  988. shape_id = self.app.tool_shapes.add(tolerance=self.drawing_tolerance, layer=0,
  989. shape=self.solid_geometry,
  990. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  991. face_color=self.app.defaults[
  992. 'global_sel_draw_color'] + 'AF',
  993. visible=True)
  994. self.poly_dict[shape_id] = self.solid_geometry
  995. added_poly_count += 1
  996. if added_poly_count > 0:
  997. self.app.tool_shapes.redraw()
  998. self.app.inform.emit(
  999. '%s: %d. %s' % (_("Added polygon"),
  1000. int(added_poly_count),
  1001. _("Click to add next polygon or right click to start isolation."))
  1002. )
  1003. else:
  1004. self.app.inform.emit(_("No polygon in selection."))
  1005. def isolate(self, iso_type=None, geometry=None, dia=None, passes=None, overlap=None, outname=None, combine=None,
  1006. milling_type=None, follow=None, plot=True):
  1007. """
  1008. Creates an isolation routing geometry object in the project.
  1009. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  1010. :param geometry: specific geometry to isolate
  1011. :param dia: Tool diameter
  1012. :param passes: Number of tool widths to cut
  1013. :param overlap: Overlap between passes in fraction of tool diameter
  1014. :param outname: Base name of the output object
  1015. :param combine: Boolean: if to combine passes in one resulting object in case of multiple passes
  1016. :param milling_type: type of milling: conventional or climbing
  1017. :param follow: Boolean: if to generate a 'follow' geometry
  1018. :param plot: Boolean: if to plot the resulting geometry object
  1019. :return: None
  1020. """
  1021. if geometry is None:
  1022. if follow:
  1023. work_geo = self.follow_geometry
  1024. else:
  1025. work_geo = self.solid_geometry
  1026. else:
  1027. work_geo = geometry
  1028. if dia is None:
  1029. dia = float(self.options["isotooldia"])
  1030. if passes is None:
  1031. passes = int(self.options["isopasses"])
  1032. if overlap is None:
  1033. overlap = float(self.options["isooverlap"])
  1034. if combine is None:
  1035. combine = self.options["combine_passes"]
  1036. else:
  1037. combine = bool(combine)
  1038. if milling_type is None:
  1039. milling_type = self.options["milling_type"]
  1040. if iso_type is None:
  1041. iso_t = 2
  1042. else:
  1043. iso_t = iso_type
  1044. base_name = self.options["name"]
  1045. if combine:
  1046. if outname is None:
  1047. if self.iso_type == 0:
  1048. iso_name = base_name + "_ext_iso"
  1049. elif self.iso_type == 1:
  1050. iso_name = base_name + "_int_iso"
  1051. else:
  1052. iso_name = base_name + "_iso"
  1053. else:
  1054. iso_name = outname
  1055. # TODO: This is ugly. Create way to pass data into init function.
  1056. def iso_init(geo_obj, app_obj):
  1057. # Propagate options
  1058. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  1059. geo_obj.tool_type = self.ui.tool_type_radio.get_value().upper()
  1060. geo_obj.solid_geometry = []
  1061. for i in range(passes):
  1062. iso_offset = dia * ((2 * i + 1) / 2.0) - (i * (overlap / 100) * dia)
  1063. # if milling type is climb then the move is counter-clockwise around features
  1064. mill_t = 1 if milling_type == 'cl' else 0
  1065. geom = self.generate_envelope(iso_offset, mill_t, geometry=work_geo, env_iso_type=iso_t,
  1066. follow=follow, nr_passes=i)
  1067. if geom == 'fail':
  1068. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1069. return 'fail'
  1070. geo_obj.solid_geometry.append(geom)
  1071. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  1072. if self.ui.tool_type_radio.get_value() == 'v':
  1073. new_cutz = self.ui.cutz_spinner.get_value()
  1074. new_vtipdia = self.ui.tipdia_spinner.get_value()
  1075. new_vtipangle = self.ui.tipangle_spinner.get_value()
  1076. tool_type = 'V'
  1077. else:
  1078. new_cutz = self.app.defaults['geometry_cutz']
  1079. new_vtipdia = self.app.defaults['geometry_vtipdia']
  1080. new_vtipangle = self.app.defaults['geometry_vtipangle']
  1081. tool_type = 'C1'
  1082. # store here the default data for Geometry Data
  1083. default_data = {}
  1084. default_data.update({
  1085. "name": iso_name,
  1086. "plot": self.app.defaults['geometry_plot'],
  1087. "cutz": new_cutz,
  1088. "vtipdia": new_vtipdia,
  1089. "vtipangle": new_vtipangle,
  1090. "travelz": self.app.defaults['geometry_travelz'],
  1091. "feedrate": self.app.defaults['geometry_feedrate'],
  1092. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  1093. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  1094. "dwell": self.app.defaults['geometry_dwell'],
  1095. "dwelltime": self.app.defaults['geometry_dwelltime'],
  1096. "multidepth": self.app.defaults['geometry_multidepth'],
  1097. "ppname_g": self.app.defaults['geometry_ppname_g'],
  1098. "depthperpass": self.app.defaults['geometry_depthperpass'],
  1099. "extracut": self.app.defaults['geometry_extracut'],
  1100. "extracut_length": self.app.defaults['geometry_extracut_length'],
  1101. "toolchange": self.app.defaults['geometry_toolchange'],
  1102. "toolchangez": self.app.defaults['geometry_toolchangez'],
  1103. "endz": self.app.defaults['geometry_endz'],
  1104. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  1105. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  1106. "startz": self.app.defaults['geometry_startz']
  1107. })
  1108. geo_obj.tools = dict()
  1109. geo_obj.tools['1'] = dict()
  1110. geo_obj.tools.update({
  1111. '1': {
  1112. 'tooldia': float(self.options["isotooldia"]),
  1113. 'offset': 'Path',
  1114. 'offset_value': 0.0,
  1115. 'type': _('Rough'),
  1116. 'tool_type': tool_type,
  1117. 'data': default_data,
  1118. 'solid_geometry': geo_obj.solid_geometry
  1119. }
  1120. })
  1121. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1122. # or just looking in the lists (they are one level depth) and if any is not empty
  1123. # proceed with object creation, if there are empty and the number of them is the length
  1124. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1125. empty_cnt = 0
  1126. if not isinstance(geo_obj.solid_geometry, list) and \
  1127. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  1128. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1129. for g in geo_obj.solid_geometry:
  1130. if g:
  1131. break
  1132. else:
  1133. empty_cnt += 1
  1134. if empty_cnt == len(geo_obj.solid_geometry):
  1135. raise ValidationError("Empty Geometry", None)
  1136. else:
  1137. app_obj.inform.emit('[success] %s" %s' %
  1138. (_("Isolation geometry created"), geo_obj.options["name"]))
  1139. # even if combine is checked, one pass is still single-geo
  1140. geo_obj.multigeo = True if passes > 1 else False
  1141. # ############################################################
  1142. # ########## AREA SUBTRACTION ################################
  1143. # ############################################################
  1144. if self.ui.except_cb.get_value():
  1145. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1146. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1147. # TODO: Do something if this is None. Offer changing name?
  1148. self.app.new_object("geometry", iso_name, iso_init, plot=plot)
  1149. else:
  1150. for i in range(passes):
  1151. offset = dia * ((2 * i + 1) / 2.0) - (i * (overlap / 100) * dia)
  1152. if passes > 1:
  1153. if outname is None:
  1154. if self.iso_type == 0:
  1155. iso_name = base_name + "_ext_iso" + str(i + 1)
  1156. elif self.iso_type == 1:
  1157. iso_name = base_name + "_int_iso" + str(i + 1)
  1158. else:
  1159. iso_name = base_name + "_iso" + str(i + 1)
  1160. else:
  1161. iso_name = outname
  1162. else:
  1163. if outname is None:
  1164. if self.iso_type == 0:
  1165. iso_name = base_name + "_ext_iso"
  1166. elif self.iso_type == 1:
  1167. iso_name = base_name + "_int_iso"
  1168. else:
  1169. iso_name = base_name + "_iso"
  1170. else:
  1171. iso_name = outname
  1172. # TODO: This is ugly. Create way to pass data into init function.
  1173. def iso_init(geo_obj, app_obj):
  1174. # Propagate options
  1175. geo_obj.options["cnctooldia"] = str(self.options["isotooldia"])
  1176. geo_obj.tool_type = self.ui.tool_type_radio.get_value().upper()
  1177. # if milling type is climb then the move is counter-clockwise around features
  1178. mill_t = 1 if milling_type == 'cl' else 0
  1179. mill_t = 1 if milling_type == 'cl' else 0
  1180. geom = self.generate_envelope(offset, mill_t, geometry=work_geo, env_iso_type=iso_t,
  1181. follow=follow,
  1182. nr_passes=i)
  1183. if geom == 'fail':
  1184. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1185. _("Isolation geometry could not be generated."))
  1186. return 'fail'
  1187. geo_obj.solid_geometry = geom
  1188. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  1189. # or just looking in the lists (they are one level depth) and if any is not empty
  1190. # proceed with object creation, if there are empty and the number of them is the length
  1191. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  1192. empty_cnt = 0
  1193. if not isinstance(geo_obj.solid_geometry, list):
  1194. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  1195. for g in geo_obj.solid_geometry:
  1196. if g:
  1197. break
  1198. else:
  1199. empty_cnt += 1
  1200. if empty_cnt == len(geo_obj.solid_geometry):
  1201. raise ValidationError("Empty Geometry", None)
  1202. else:
  1203. app_obj.inform.emit('[success] %s: %s' %
  1204. (_("Isolation geometry created"), geo_obj.options["name"]))
  1205. geo_obj.multigeo = False
  1206. # ############################################################
  1207. # ########## AREA SUBTRACTION ################################
  1208. # ############################################################
  1209. if self.ui.except_cb.get_value():
  1210. self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  1211. geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  1212. # TODO: Do something if this is None. Offer changing name?
  1213. self.app.new_object("geometry", iso_name, iso_init, plot=plot)
  1214. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  1215. # isolation_geometry produces an envelope that is going on the left of the geometry
  1216. # (the copper features). To leave the least amount of burrs on the features
  1217. # the tool needs to travel on the right side of the features (this is called conventional milling)
  1218. # the first pass is the one cutting all of the features, so it needs to be reversed
  1219. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  1220. # to cut on the right side of the left over copper i.e on the left side of the features.
  1221. if follow:
  1222. geom = self.isolation_geometry(offset, geometry=geometry, follow=follow)
  1223. else:
  1224. try:
  1225. geom = self.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type, passes=nr_passes)
  1226. except Exception as e:
  1227. log.debug('FlatCAMGerber.isolate().generate_envelope() --> %s' % str(e))
  1228. return 'fail'
  1229. if invert:
  1230. try:
  1231. pl = []
  1232. for p in geom:
  1233. if p is not None:
  1234. if isinstance(p, Polygon):
  1235. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  1236. elif isinstance(p, LinearRing):
  1237. pl.append(Polygon(p.coords[::-1]))
  1238. geom = MultiPolygon(pl)
  1239. except TypeError:
  1240. if isinstance(geom, Polygon) and geom is not None:
  1241. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  1242. elif isinstance(geom, LinearRing) and geom is not None:
  1243. geom = Polygon(geom.coords[::-1])
  1244. else:
  1245. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry %s" %
  1246. type(geom))
  1247. except Exception as e:
  1248. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  1249. return 'fail'
  1250. return geom
  1251. def area_subtraction(self, geo, subtractor_geo=None):
  1252. """
  1253. Subtracts the subtractor_geo (if present else self.solid_geometry) from the geo
  1254. :param geo: target geometry from which to subtract
  1255. :param subtractor_geo: geometry that acts as subtractor
  1256. :return:
  1257. """
  1258. new_geometry = []
  1259. target_geo = geo
  1260. if subtractor_geo:
  1261. sub_union = cascaded_union(subtractor_geo)
  1262. else:
  1263. name = self.ui.obj_combo.currentText()
  1264. subtractor_obj = self.app.collection.get_by_name(name)
  1265. sub_union = cascaded_union(subtractor_obj.solid_geometry)
  1266. try:
  1267. for geo_elem in target_geo:
  1268. if isinstance(geo_elem, Polygon):
  1269. for ring in self.poly2rings(geo_elem):
  1270. new_geo = ring.difference(sub_union)
  1271. if new_geo and not new_geo.is_empty:
  1272. new_geometry.append(new_geo)
  1273. elif isinstance(geo_elem, MultiPolygon):
  1274. for poly in geo_elem:
  1275. for ring in self.poly2rings(poly):
  1276. new_geo = ring.difference(sub_union)
  1277. if new_geo and not new_geo.is_empty:
  1278. new_geometry.append(new_geo)
  1279. elif isinstance(geo_elem, LineString):
  1280. new_geo = geo_elem.difference(sub_union)
  1281. if new_geo:
  1282. if not new_geo.is_empty:
  1283. new_geometry.append(new_geo)
  1284. elif isinstance(geo_elem, MultiLineString):
  1285. for line_elem in geo_elem:
  1286. new_geo = line_elem.difference(sub_union)
  1287. if new_geo and not new_geo.is_empty:
  1288. new_geometry.append(new_geo)
  1289. except TypeError:
  1290. if isinstance(target_geo, Polygon):
  1291. for ring in self.poly2rings(target_geo):
  1292. new_geo = ring.difference(sub_union)
  1293. if new_geo:
  1294. if not new_geo.is_empty:
  1295. new_geometry.append(new_geo)
  1296. elif isinstance(target_geo, LineString):
  1297. new_geo = target_geo.difference(sub_union)
  1298. if new_geo and not new_geo.is_empty:
  1299. new_geometry.append(new_geo)
  1300. elif isinstance(target_geo, MultiLineString):
  1301. for line_elem in target_geo:
  1302. new_geo = line_elem.difference(sub_union)
  1303. if new_geo and not new_geo.is_empty:
  1304. new_geometry.append(new_geo)
  1305. return new_geometry
  1306. def on_plot_cb_click(self, *args):
  1307. if self.muted_ui:
  1308. return
  1309. self.read_form_item('plot')
  1310. self.plot()
  1311. def on_solid_cb_click(self, *args):
  1312. if self.muted_ui:
  1313. return
  1314. self.read_form_item('solid')
  1315. self.plot()
  1316. def on_multicolored_cb_click(self, *args):
  1317. if self.muted_ui:
  1318. return
  1319. self.read_form_item('multicolored')
  1320. self.plot()
  1321. def on_follow_cb_click(self):
  1322. if self.muted_ui:
  1323. return
  1324. self.plot()
  1325. def on_aperture_table_visibility_change(self):
  1326. if self.ui.aperture_table_visibility_cb.isChecked():
  1327. # add the shapes storage for marking apertures
  1328. if self.app.is_legacy is False:
  1329. for ap_code in self.apertures:
  1330. self.mark_shapes[ap_code] = self.app.plotcanvas.new_shape_collection(layers=1)
  1331. else:
  1332. for ap_code in self.apertures:
  1333. self.mark_shapes[ap_code] = ShapeCollectionLegacy(obj=self, app=self.app,
  1334. name=self.options['name'] + str(ap_code))
  1335. self.ui.apertures_table.setVisible(True)
  1336. for ap in self.mark_shapes:
  1337. self.mark_shapes[ap].enabled = True
  1338. self.ui.mark_all_cb.setVisible(True)
  1339. self.ui.mark_all_cb.setChecked(False)
  1340. else:
  1341. self.ui.apertures_table.setVisible(False)
  1342. self.ui.mark_all_cb.setVisible(False)
  1343. # on hide disable all mark plots
  1344. try:
  1345. for row in range(self.ui.apertures_table.rowCount()):
  1346. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  1347. self.clear_plot_apertures()
  1348. for ap in list(self.mark_shapes.keys()):
  1349. # self.mark_shapes[ap].enabled = False
  1350. del self.mark_shapes[ap]
  1351. except Exception as e:
  1352. log.debug(" FlatCAMGerber.on_aperture_visibility_changed() --> %s" % str(e))
  1353. def convert_units(self, units):
  1354. """
  1355. Converts the units of the object by scaling dimensions in all geometry
  1356. and options.
  1357. :param units: Units to which to convert the object: "IN" or "MM".
  1358. :type units: str
  1359. :return: None
  1360. :rtype: None
  1361. """
  1362. # units conversion to get a conversion should be done only once even if we found multiple
  1363. # units declaration inside a Gerber file (it can happen to find also the obsolete declaration)
  1364. if self.conversion_done is True:
  1365. log.debug("Gerber units conversion cancelled. Already done.")
  1366. return
  1367. log.debug("FlatCAMObj.FlatCAMGerber.convert_units()")
  1368. factor = Gerber.convert_units(self, units)
  1369. # self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  1370. # self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  1371. def plot(self, **kwargs):
  1372. """
  1373. :param kwargs: color and face_color
  1374. :return:
  1375. """
  1376. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  1377. # Does all the required setup and returns False
  1378. # if the 'ptint' option is set to False.
  1379. if not FlatCAMObj.plot(self):
  1380. return
  1381. if 'color' in kwargs:
  1382. color = kwargs['color']
  1383. else:
  1384. color = self.outline_color
  1385. if 'face_color' in kwargs:
  1386. face_color = kwargs['face_color']
  1387. else:
  1388. face_color = self.fill_color
  1389. if 'visible' not in kwargs:
  1390. visible = self.options['plot']
  1391. else:
  1392. visible = kwargs['visible']
  1393. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  1394. if self.ui.follow_cb.get_value():
  1395. geometry = self.follow_geometry
  1396. else:
  1397. geometry = self.solid_geometry
  1398. # Make sure geometry is iterable.
  1399. try:
  1400. __ = iter(geometry)
  1401. except TypeError:
  1402. geometry = [geometry]
  1403. if self.app.is_legacy is False:
  1404. def random_color():
  1405. r_color = np.random.rand(4)
  1406. r_color[3] = 1
  1407. return r_color
  1408. else:
  1409. def random_color():
  1410. while True:
  1411. r_color = np.random.rand(4)
  1412. r_color[3] = 1
  1413. new_color = '#'
  1414. for idx in range(len(r_color)):
  1415. new_color += '%x' % int(r_color[idx] * 255)
  1416. # do it until a valid color is generated
  1417. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  1418. # for a total of 9 chars
  1419. if len(new_color) == 9:
  1420. break
  1421. return new_color
  1422. try:
  1423. if self.options["solid"]:
  1424. for g in geometry:
  1425. if type(g) == Polygon or type(g) == LineString:
  1426. self.add_shape(shape=g, color=color,
  1427. face_color=random_color() if self.options['multicolored']
  1428. else face_color, visible=visible)
  1429. elif type(g) == Point:
  1430. pass
  1431. else:
  1432. try:
  1433. for el in g:
  1434. self.add_shape(shape=el, color=color,
  1435. face_color=random_color() if self.options['multicolored']
  1436. else face_color, visible=visible)
  1437. except TypeError:
  1438. self.add_shape(shape=g, color=color,
  1439. face_color=random_color() if self.options['multicolored']
  1440. else face_color, visible=visible)
  1441. else:
  1442. for g in geometry:
  1443. if type(g) == Polygon or type(g) == LineString:
  1444. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  1445. visible=visible)
  1446. elif type(g) == Point:
  1447. pass
  1448. else:
  1449. for el in g:
  1450. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  1451. visible=visible)
  1452. self.shapes.redraw(
  1453. # update_colors=(self.fill_color, self.outline_color),
  1454. # indexes=self.app.plotcanvas.shape_collection.data.keys()
  1455. )
  1456. except (ObjectDeleted, AttributeError):
  1457. self.shapes.clear(update=True)
  1458. except Exception as e:
  1459. log.debug("FlatCAMGerber.plot() --> %s" % str(e))
  1460. # experimental plot() when the solid_geometry is stored in the self.apertures
  1461. def plot_aperture(self, run_thread=True, **kwargs):
  1462. """
  1463. :param run_thread: if True run the aperture plot as a thread in a worker
  1464. :param kwargs: color and face_color
  1465. :return:
  1466. """
  1467. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot_aperture()")
  1468. # Does all the required setup and returns False
  1469. # if the 'ptint' option is set to False.
  1470. # if not FlatCAMObj.plot(self):
  1471. # return
  1472. # for marking apertures, line color and fill color are the same
  1473. if 'color' in kwargs:
  1474. color = kwargs['color']
  1475. else:
  1476. color = self.app.defaults['global_plot_fill']
  1477. if 'marked_aperture' not in kwargs:
  1478. return
  1479. else:
  1480. aperture_to_plot_mark = kwargs['marked_aperture']
  1481. if aperture_to_plot_mark is None:
  1482. return
  1483. if 'visible' not in kwargs:
  1484. visibility = True
  1485. else:
  1486. visibility = kwargs['visible']
  1487. with self.app.proc_container.new(_("Plotting Apertures")):
  1488. self.app.progress.emit(30)
  1489. def job_thread(app_obj):
  1490. try:
  1491. if aperture_to_plot_mark in self.apertures:
  1492. for elem in self.apertures[aperture_to_plot_mark]['geometry']:
  1493. if 'solid' in elem:
  1494. geo = elem['solid']
  1495. if type(geo) == Polygon or type(geo) == LineString:
  1496. self.add_mark_shape(apid=aperture_to_plot_mark, shape=geo, color=color,
  1497. face_color=color, visible=visibility)
  1498. else:
  1499. for el in geo:
  1500. self.add_mark_shape(apid=aperture_to_plot_mark, shape=el, color=color,
  1501. face_color=color, visible=visibility)
  1502. self.mark_shapes[aperture_to_plot_mark].redraw()
  1503. except (ObjectDeleted, AttributeError):
  1504. self.clear_plot_apertures()
  1505. except Exception as e:
  1506. log.debug("FlatCAMGerber.plot_aperture() --> %s" % str(e))
  1507. if run_thread:
  1508. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  1509. else:
  1510. job_thread(self)
  1511. def clear_plot_apertures(self, aperture='all'):
  1512. """
  1513. :param aperture: string; aperture for which to clear the mark shapes
  1514. :return:
  1515. """
  1516. if self.mark_shapes:
  1517. if aperture == 'all':
  1518. for apid in list(self.apertures.keys()):
  1519. try:
  1520. if self.app.is_legacy is True:
  1521. self.mark_shapes[apid].clear(update=False)
  1522. else:
  1523. self.mark_shapes[apid].clear(update=True)
  1524. except Exception as e:
  1525. log.debug("FlatCAMGerber.clear_plot_apertures() 'all' --> %s" % str(e))
  1526. else:
  1527. try:
  1528. if self.app.is_legacy is True:
  1529. self.mark_shapes[aperture].clear(update=False)
  1530. else:
  1531. self.mark_shapes[aperture].clear(update=True)
  1532. except Exception as e:
  1533. log.debug("FlatCAMGerber.clear_plot_apertures() 'aperture' --> %s" % str(e))
  1534. def clear_mark_all(self):
  1535. self.ui.mark_all_cb.set_value(False)
  1536. self.marked_rows[:] = []
  1537. def on_mark_cb_click_table(self):
  1538. """
  1539. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  1540. :return:
  1541. """
  1542. self.ui_disconnect()
  1543. cw = self.sender()
  1544. try:
  1545. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  1546. cw_row = cw_index.row()
  1547. except AttributeError:
  1548. cw_row = 0
  1549. except TypeError:
  1550. return
  1551. self.marked_rows[:] = []
  1552. try:
  1553. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  1554. except AttributeError:
  1555. return
  1556. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  1557. self.marked_rows.append(True)
  1558. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1559. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1560. marked_aperture=aperture, visible=True, run_thread=True)
  1561. # self.mark_shapes[aperture].redraw()
  1562. else:
  1563. self.marked_rows.append(False)
  1564. self.clear_plot_apertures(aperture=aperture)
  1565. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  1566. # if all the row mark's are enabled also enable the Mark All checkbox
  1567. cb_cnt = 0
  1568. total_row = self.ui.apertures_table.rowCount()
  1569. for row in range(total_row):
  1570. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  1571. cb_cnt += 1
  1572. else:
  1573. cb_cnt -= 1
  1574. if cb_cnt < total_row:
  1575. self.ui.mark_all_cb.setChecked(False)
  1576. else:
  1577. self.ui.mark_all_cb.setChecked(True)
  1578. self.ui_connect()
  1579. def on_mark_all_click(self, signal):
  1580. self.ui_disconnect()
  1581. mark_all = self.ui.mark_all_cb.isChecked()
  1582. for row in range(self.ui.apertures_table.rowCount()):
  1583. # update the mark_rows list
  1584. if mark_all:
  1585. self.marked_rows.append(True)
  1586. else:
  1587. self.marked_rows[:] = []
  1588. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  1589. mark_cb.setChecked(mark_all)
  1590. if mark_all:
  1591. for aperture in self.apertures:
  1592. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  1593. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1594. marked_aperture=aperture, visible=True)
  1595. # HACK: enable/disable the grid for a better look
  1596. self.app.ui.grid_snap_btn.trigger()
  1597. self.app.ui.grid_snap_btn.trigger()
  1598. else:
  1599. self.clear_plot_apertures()
  1600. self.marked_rows[:] = []
  1601. self.ui_connect()
  1602. def export_gerber(self, whole, fract, g_zeros='L', factor=1):
  1603. """
  1604. Creates a Gerber file content to be exported to a file.
  1605. :param whole: how many digits in the whole part of coordinates
  1606. :param fract: how many decimals in coordinates
  1607. :param g_zeros: type of the zero suppression used: LZ or TZ; string
  1608. :param factor: factor to be applied onto the Gerber coordinates
  1609. :return: Gerber_code
  1610. """
  1611. log.debug("FlatCAMGerber.export_gerber() --> Generating the Gerber code from the selected Gerber file")
  1612. def tz_format(x, y, fac):
  1613. x_c = x * fac
  1614. y_c = y * fac
  1615. x_form = "{:.{dec}f}".format(x_c, dec=fract)
  1616. y_form = "{:.{dec}f}".format(y_c, dec=fract)
  1617. # extract whole part and decimal part
  1618. x_form = x_form.partition('.')
  1619. y_form = y_form.partition('.')
  1620. # left padd the 'whole' part with zeros
  1621. x_whole = x_form[0].rjust(whole, '0')
  1622. y_whole = y_form[0].rjust(whole, '0')
  1623. # restore the coordinate padded in the left with 0 and added the decimal part
  1624. # without the decinal dot
  1625. x_form = x_whole + x_form[2]
  1626. y_form = y_whole + y_form[2]
  1627. return x_form, y_form
  1628. def lz_format(x, y, fac):
  1629. x_c = x * fac
  1630. y_c = y * fac
  1631. x_form = "{:.{dec}f}".format(x_c, dec=fract).replace('.', '')
  1632. y_form = "{:.{dec}f}".format(y_c, dec=fract).replace('.', '')
  1633. # pad with rear zeros
  1634. x_form.ljust(length, '0')
  1635. y_form.ljust(length, '0')
  1636. return x_form, y_form
  1637. # Gerber code is stored here
  1638. gerber_code = ''
  1639. # apertures processing
  1640. try:
  1641. length = whole + fract
  1642. if '0' in self.apertures:
  1643. if 'geometry' in self.apertures['0']:
  1644. for geo_elem in self.apertures['0']['geometry']:
  1645. if 'solid' in geo_elem:
  1646. geo = geo_elem['solid']
  1647. if not geo.is_empty:
  1648. gerber_code += 'G36*\n'
  1649. geo_coords = list(geo.exterior.coords)
  1650. # first command is a move with pen-up D02 at the beginning of the geo
  1651. if g_zeros == 'T':
  1652. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1653. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1654. yform=y_formatted)
  1655. else:
  1656. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1657. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1658. yform=y_formatted)
  1659. for coord in geo_coords[1:]:
  1660. if g_zeros == 'T':
  1661. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1662. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1663. yform=y_formatted)
  1664. else:
  1665. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1666. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1667. yform=y_formatted)
  1668. gerber_code += 'D02*\n'
  1669. gerber_code += 'G37*\n'
  1670. clear_list = list(geo.interiors)
  1671. if clear_list:
  1672. gerber_code += '%LPC*%\n'
  1673. for clear_geo in clear_list:
  1674. gerber_code += 'G36*\n'
  1675. geo_coords = list(clear_geo.coords)
  1676. # first command is a move with pen-up D02 at the beginning of the geo
  1677. if g_zeros == 'T':
  1678. x_formatted, y_formatted = tz_format(
  1679. geo_coords[0][0], geo_coords[0][1], factor)
  1680. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1681. yform=y_formatted)
  1682. else:
  1683. x_formatted, y_formatted = lz_format(
  1684. geo_coords[0][0], geo_coords[0][1], factor)
  1685. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1686. yform=y_formatted)
  1687. prev_coord = geo_coords[0]
  1688. for coord in geo_coords[1:]:
  1689. if coord != prev_coord:
  1690. if g_zeros == 'T':
  1691. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1692. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1693. yform=y_formatted)
  1694. else:
  1695. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1696. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1697. yform=y_formatted)
  1698. prev_coord = coord
  1699. gerber_code += 'D02*\n'
  1700. gerber_code += 'G37*\n'
  1701. gerber_code += '%LPD*%\n'
  1702. if 'clear' in geo_elem:
  1703. geo = geo_elem['clear']
  1704. if not geo.is_empty:
  1705. gerber_code += '%LPC*%\n'
  1706. gerber_code += 'G36*\n'
  1707. geo_coords = list(geo.exterior.coords)
  1708. # first command is a move with pen-up D02 at the beginning of the geo
  1709. if g_zeros == 'T':
  1710. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1711. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1712. yform=y_formatted)
  1713. else:
  1714. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1715. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1716. yform=y_formatted)
  1717. prev_coord = geo_coords[0]
  1718. for coord in geo_coords[1:]:
  1719. if coord != prev_coord:
  1720. if g_zeros == 'T':
  1721. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1722. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1723. yform=y_formatted)
  1724. else:
  1725. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1726. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1727. yform=y_formatted)
  1728. prev_coord = coord
  1729. gerber_code += 'D02*\n'
  1730. gerber_code += 'G37*\n'
  1731. gerber_code += '%LPD*%\n'
  1732. for apid in self.apertures:
  1733. if apid == '0':
  1734. continue
  1735. else:
  1736. gerber_code += 'D%s*\n' % str(apid)
  1737. if 'geometry' in self.apertures[apid]:
  1738. for geo_elem in self.apertures[apid]['geometry']:
  1739. if 'follow' in geo_elem:
  1740. geo = geo_elem['follow']
  1741. if not geo.is_empty:
  1742. if isinstance(geo, Point):
  1743. if g_zeros == 'T':
  1744. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1745. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1746. yform=y_formatted)
  1747. else:
  1748. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1749. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1750. yform=y_formatted)
  1751. else:
  1752. geo_coords = list(geo.coords)
  1753. # first command is a move with pen-up D02 at the beginning of the geo
  1754. if g_zeros == 'T':
  1755. x_formatted, y_formatted = tz_format(
  1756. geo_coords[0][0], geo_coords[0][1], factor)
  1757. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1758. yform=y_formatted)
  1759. else:
  1760. x_formatted, y_formatted = lz_format(
  1761. geo_coords[0][0], geo_coords[0][1], factor)
  1762. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1763. yform=y_formatted)
  1764. prev_coord = geo_coords[0]
  1765. for coord in geo_coords[1:]:
  1766. if coord != prev_coord:
  1767. if g_zeros == 'T':
  1768. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1769. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1770. yform=y_formatted)
  1771. else:
  1772. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1773. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1774. yform=y_formatted)
  1775. prev_coord = coord
  1776. # gerber_code += "D02*\n"
  1777. if 'clear' in geo_elem:
  1778. gerber_code += '%LPC*%\n'
  1779. geo = geo_elem['clear']
  1780. if not geo.is_empty:
  1781. if isinstance(geo, Point):
  1782. if g_zeros == 'T':
  1783. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1784. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1785. yform=y_formatted)
  1786. else:
  1787. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1788. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1789. yform=y_formatted)
  1790. else:
  1791. geo_coords = list(geo.coords)
  1792. # first command is a move with pen-up D02 at the beginning of the geo
  1793. if g_zeros == 'T':
  1794. x_formatted, y_formatted = tz_format(
  1795. geo_coords[0][0], geo_coords[0][1], factor)
  1796. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1797. yform=y_formatted)
  1798. else:
  1799. x_formatted, y_formatted = lz_format(
  1800. geo_coords[0][0], geo_coords[0][1], factor)
  1801. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1802. yform=y_formatted)
  1803. prev_coord = geo_coords[0]
  1804. for coord in geo_coords[1:]:
  1805. if coord != prev_coord:
  1806. if g_zeros == 'T':
  1807. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1808. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1809. yform=y_formatted)
  1810. else:
  1811. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1812. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1813. yform=y_formatted)
  1814. prev_coord = coord
  1815. # gerber_code += "D02*\n"
  1816. gerber_code += '%LPD*%\n'
  1817. except Exception as e:
  1818. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> %s" % str(e))
  1819. if not self.apertures:
  1820. log.debug("FlatCAMObj.FlatCAMGerber.export_gerber() --> Gerber Object is empty: no apertures.")
  1821. return 'fail'
  1822. return gerber_code
  1823. def mirror(self, axis, point):
  1824. Gerber.mirror(self, axis=axis, point=point)
  1825. self.replotApertures.emit()
  1826. def offset(self, vect):
  1827. Gerber.offset(self, vect=vect)
  1828. self.replotApertures.emit()
  1829. def rotate(self, angle, point):
  1830. Gerber.rotate(self, angle=angle, point=point)
  1831. self.replotApertures.emit()
  1832. def scale(self, xfactor, yfactor=None, point=None):
  1833. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  1834. self.replotApertures.emit()
  1835. def skew(self, angle_x, angle_y, point):
  1836. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1837. self.replotApertures.emit()
  1838. def buffer(self, distance, join):
  1839. Gerber.buffer(self, distance=distance, join=join)
  1840. self.replotApertures.emit()
  1841. def serialize(self):
  1842. return {
  1843. "options": self.options,
  1844. "kind": self.kind
  1845. }
  1846. class FlatCAMExcellon(FlatCAMObj, Excellon):
  1847. """
  1848. Represents Excellon/Drill code.
  1849. """
  1850. ui_type = ExcellonObjectUI
  1851. optionChanged = QtCore.pyqtSignal(str)
  1852. def __init__(self, name):
  1853. self.decimals = self.app.decimals
  1854. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  1855. Excellon.__init__(self, geo_steps_per_circle=self.circle_steps)
  1856. FlatCAMObj.__init__(self, name)
  1857. self.kind = "excellon"
  1858. self.options.update({
  1859. "plot": True,
  1860. "solid": False,
  1861. "drillz": -0.1,
  1862. "travelz": 0.1,
  1863. "feedrate": 5.0,
  1864. "feedrate_rapid": 5.0,
  1865. "tooldia": 0.1,
  1866. "slot_tooldia": 0.1,
  1867. "toolchange": False,
  1868. "toolchangez": 1.0,
  1869. "toolchangexy": "0.0, 0.0",
  1870. "endz": 2.0,
  1871. "startz": None,
  1872. "spindlespeed": 0,
  1873. "dwell": True,
  1874. "dwelltime": 1000,
  1875. "ppname_e": 'defaults',
  1876. "z_pdepth": -0.02,
  1877. "feedrate_probe": 3.0,
  1878. "optimization_type": "R",
  1879. "gcode_type": "drills"
  1880. })
  1881. # TODO: Document this.
  1882. self.tool_cbs = dict()
  1883. # dict to hold the tool number as key and tool offset as value
  1884. self.tool_offset = dict()
  1885. # variable to store the total amount of drills per job
  1886. self.tot_drill_cnt = 0
  1887. self.tool_row = 0
  1888. # variable to store the total amount of slots per job
  1889. self.tot_slot_cnt = 0
  1890. self.tool_row_slots = 0
  1891. # variable to store the distance travelled
  1892. self.travel_distance = 0.0
  1893. # store the source file here
  1894. self.source_file = ""
  1895. self.multigeo = False
  1896. self.units_found = self.app.defaults['units']
  1897. # Attributes to be included in serialization
  1898. # Always append to it because it carries contents
  1899. # from predecessors.
  1900. self.ser_attrs += ['options', 'kind']
  1901. def merge(self, exc_list, exc_final):
  1902. """
  1903. Merge Excellon objects found in exc_list parameter into exc_final object.
  1904. Options are always copied from source .
  1905. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  1906. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  1907. tool_name to be used in the final Excellon object, exc_final.
  1908. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  1909. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  1910. :param exc_final: Destination FlatCAMExcellon object.
  1911. :return: None
  1912. """
  1913. try:
  1914. decimals_exc = self.decimals
  1915. except AttributeError:
  1916. decimals_exc = 4
  1917. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  1918. flag_order = False
  1919. try:
  1920. flattened_list = list(itertools.chain(*exc_list))
  1921. except TypeError:
  1922. flattened_list = exc_list
  1923. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1924. # values will be list of Shapely Points; for drills
  1925. custom_dict_drills = {}
  1926. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  1927. # values will be list of Shapely Points; for slots
  1928. custom_dict_slots = {}
  1929. for exc in flattened_list:
  1930. # copy options of the current excellon obj to the final excellon obj
  1931. for option in exc.options:
  1932. if option is not 'name':
  1933. try:
  1934. exc_final.options[option] = exc.options[option]
  1935. except Exception as e:
  1936. exc.app.log.warning("Failed to copy option.", option)
  1937. for drill in exc.drills:
  1938. exc_tool_dia = float('%.*f' % (decimals_exc, exc.tools[drill['tool']]['C']))
  1939. if exc_tool_dia not in custom_dict_drills:
  1940. custom_dict_drills[exc_tool_dia] = [drill['point']]
  1941. else:
  1942. custom_dict_drills[exc_tool_dia].append(drill['point'])
  1943. for slot in exc.slots:
  1944. exc_tool_dia = float('%.*f' % (decimals_exc, exc.tools[slot['tool']]['C']))
  1945. if exc_tool_dia not in custom_dict_slots:
  1946. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  1947. else:
  1948. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  1949. # add the zeros and units to the exc_final object
  1950. exc_final.zeros = exc.zeros
  1951. exc_final.units = exc.units
  1952. # ##########################################
  1953. # Here we add data to the exc_final object #
  1954. # ##########################################
  1955. # variable to make tool_name for the tools
  1956. current_tool = 0
  1957. # The tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  1958. # drills
  1959. for tool_dia in custom_dict_drills:
  1960. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  1961. current_tool += 1
  1962. tool_name = str(current_tool)
  1963. spec = {"C": float(tool_dia)}
  1964. exc_final.tools[tool_name] = spec
  1965. # rebuild the drills list of dict's that belong to the exc_final object
  1966. for point in custom_dict_drills[tool_dia]:
  1967. exc_final.drills.append(
  1968. {
  1969. "point": point,
  1970. "tool": str(current_tool)
  1971. }
  1972. )
  1973. # The tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  1974. # of two Shapely Points in case of slots
  1975. for tool_dia in custom_dict_slots:
  1976. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  1977. # but only if there are no drills
  1978. if not exc_final.tools:
  1979. current_tool += 1
  1980. tool_name = str(current_tool)
  1981. spec = {"C": float(tool_dia)}
  1982. exc_final.tools[tool_name] = spec
  1983. else:
  1984. dia_list = []
  1985. for v in exc_final.tools.values():
  1986. dia_list.append(float(v["C"]))
  1987. if tool_dia not in dia_list:
  1988. flag_order = True
  1989. current_tool = len(dia_list) + 1
  1990. tool_name = str(current_tool)
  1991. spec = {"C": float(tool_dia)}
  1992. exc_final.tools[tool_name] = spec
  1993. else:
  1994. for k, v in exc_final.tools.items():
  1995. if v["C"] == tool_dia:
  1996. current_tool = int(k)
  1997. break
  1998. # rebuild the slots list of dict's that belong to the exc_final object
  1999. for point in custom_dict_slots[tool_dia]:
  2000. exc_final.slots.append(
  2001. {
  2002. "start": point[0],
  2003. "stop": point[1],
  2004. "tool": str(current_tool)
  2005. }
  2006. )
  2007. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  2008. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  2009. current_tool = 0
  2010. if flag_order is True:
  2011. dia_list = []
  2012. temp_drills = []
  2013. temp_slots = []
  2014. temp_tools = {}
  2015. for v in exc_final.tools.values():
  2016. dia_list.append(float(v["C"]))
  2017. dia_list.sort()
  2018. for ordered_dia in dia_list:
  2019. current_tool += 1
  2020. tool_name_temp = str(current_tool)
  2021. spec_temp = {"C": float(ordered_dia)}
  2022. temp_tools[tool_name_temp] = spec_temp
  2023. for drill in exc_final.drills:
  2024. exc_tool_dia = float('%.*f' % (decimals_exc, exc_final.tools[drill['tool']]['C']))
  2025. if exc_tool_dia == ordered_dia:
  2026. temp_drills.append(
  2027. {
  2028. "point": drill["point"],
  2029. "tool": str(current_tool)
  2030. }
  2031. )
  2032. for slot in exc_final.slots:
  2033. slot_tool_dia = float('%.*f' % (decimals_exc, exc_final.tools[slot['tool']]['C']))
  2034. if slot_tool_dia == ordered_dia:
  2035. temp_slots.append(
  2036. {
  2037. "start": slot["start"],
  2038. "stop": slot["stop"],
  2039. "tool": str(current_tool)
  2040. }
  2041. )
  2042. # delete the exc_final tools, drills and slots
  2043. exc_final.tools = dict()
  2044. exc_final.drills[:] = []
  2045. exc_final.slots[:] = []
  2046. # update the exc_final tools, drills and slots with the ordered values
  2047. exc_final.tools = temp_tools
  2048. exc_final.drills[:] = temp_drills
  2049. exc_final.slots[:] = temp_slots
  2050. # create the geometry for the exc_final object
  2051. exc_final.create_geometry()
  2052. def build_ui(self):
  2053. FlatCAMObj.build_ui(self)
  2054. self.units = self.app.defaults['units'].upper()
  2055. for row in range(self.ui.tools_table.rowCount()):
  2056. try:
  2057. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2058. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2059. offset_spin_widget.valueChanged.disconnect()
  2060. except (TypeError, AttributeError):
  2061. pass
  2062. n = len(self.tools)
  2063. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  2064. self.ui.tools_table.setRowCount(n + 2)
  2065. self.tot_drill_cnt = 0
  2066. self.tot_slot_cnt = 0
  2067. self.tool_row = 0
  2068. sort = []
  2069. for k, v in list(self.tools.items()):
  2070. sort.append((k, v.get('C')))
  2071. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2072. tools = [i[0] for i in sorted_tools]
  2073. for tool_no in tools:
  2074. drill_cnt = 0 # variable to store the nr of drills per tool
  2075. slot_cnt = 0 # variable to store the nr of slots per tool
  2076. # Find no of drills for the current tool
  2077. for drill in self.drills:
  2078. if drill['tool'] == tool_no:
  2079. drill_cnt += 1
  2080. self.tot_drill_cnt += drill_cnt
  2081. # Find no of slots for the current tool
  2082. for slot in self.slots:
  2083. if slot['tool'] == tool_no:
  2084. slot_cnt += 1
  2085. self.tot_slot_cnt += slot_cnt
  2086. exc_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  2087. exc_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2088. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, self.tools[tool_no]['C']))
  2089. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2090. drill_count_item = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  2091. drill_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2092. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  2093. slot_count_str = '%d' % slot_cnt if slot_cnt > 0 else ''
  2094. slot_count_item = QtWidgets.QTableWidgetItem(slot_count_str)
  2095. slot_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2096. try:
  2097. t_offset = self.tool_offset[float('%.*f' % (self.decimals, float(self.tools[tool_no]['C'])))]
  2098. except KeyError:
  2099. t_offset = self.app.defaults['excellon_offset']
  2100. tool_offset_item = FCDoubleSpinner()
  2101. tool_offset_item.set_precision(self.decimals)
  2102. tool_offset_item.set_range(-9999.9999, 9999.9999)
  2103. tool_offset_item.setWrapping(True)
  2104. tool_offset_item.setSingleStep(0.1) if self.units == 'MM' else tool_offset_item.setSingleStep(0.01)
  2105. tool_offset_item.set_value(t_offset)
  2106. plot_item = FCCheckBox()
  2107. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2108. if self.ui.plot_cb.isChecked():
  2109. plot_item.setChecked(True)
  2110. self.ui.tools_table.setItem(self.tool_row, 0, exc_id_item) # Tool name/id
  2111. self.ui.tools_table.setItem(self.tool_row, 1, dia_item) # Diameter
  2112. self.ui.tools_table.setItem(self.tool_row, 2, drill_count_item) # Number of drills per tool
  2113. self.ui.tools_table.setItem(self.tool_row, 3, slot_count_item) # Number of drills per tool
  2114. self.ui.tools_table.setCellWidget(self.tool_row, 4, tool_offset_item) # Tool offset
  2115. empty_plot_item = QtWidgets.QTableWidgetItem('')
  2116. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2117. self.ui.tools_table.setItem(self.tool_row, 5, empty_plot_item)
  2118. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  2119. self.tool_row += 1
  2120. # add a last row with the Total number of drills
  2121. empty_1 = QtWidgets.QTableWidgetItem('')
  2122. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2123. empty_1_1 = QtWidgets.QTableWidgetItem('')
  2124. empty_1_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2125. empty_1_2 = QtWidgets.QTableWidgetItem('')
  2126. empty_1_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2127. empty_1_3 = QtWidgets.QTableWidgetItem('')
  2128. empty_1_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2129. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  2130. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  2131. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2132. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2133. self.ui.tools_table.setItem(self.tool_row, 0, empty_1)
  2134. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  2135. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  2136. self.ui.tools_table.setItem(self.tool_row, 3, empty_1_1)
  2137. self.ui.tools_table.setItem(self.tool_row, 4, empty_1_2)
  2138. self.ui.tools_table.setItem(self.tool_row, 5, empty_1_3)
  2139. font = QtGui.QFont()
  2140. font.setBold(True)
  2141. font.setWeight(75)
  2142. for k in [1, 2]:
  2143. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  2144. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  2145. self.tool_row += 1
  2146. # add a last row with the Total number of slots
  2147. empty_2 = QtWidgets.QTableWidgetItem('')
  2148. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2149. empty_2_1 = QtWidgets.QTableWidgetItem('')
  2150. empty_2_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2151. empty_2_2 = QtWidgets.QTableWidgetItem('')
  2152. empty_2_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2153. empty_2_3 = QtWidgets.QTableWidgetItem('')
  2154. empty_2_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2155. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  2156. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  2157. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2158. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  2159. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  2160. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  2161. self.ui.tools_table.setItem(self.tool_row, 2, empty_2_1)
  2162. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  2163. self.ui.tools_table.setItem(self.tool_row, 4, empty_2_2)
  2164. self.ui.tools_table.setItem(self.tool_row, 5, empty_2_3)
  2165. for kl in [1, 2, 3]:
  2166. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  2167. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  2168. # sort the tool diameter column
  2169. # self.ui.tools_table.sortItems(1)
  2170. # all the tools are selected by default
  2171. self.ui.tools_table.selectColumn(0)
  2172. #
  2173. self.ui.tools_table.resizeColumnsToContents()
  2174. self.ui.tools_table.resizeRowsToContents()
  2175. vertical_header = self.ui.tools_table.verticalHeader()
  2176. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2177. vertical_header.hide()
  2178. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2179. horizontal_header = self.ui.tools_table.horizontalHeader()
  2180. horizontal_header.setMinimumSectionSize(10)
  2181. horizontal_header.setDefaultSectionSize(70)
  2182. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2183. horizontal_header.resizeSection(0, 20)
  2184. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  2185. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  2186. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2187. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  2188. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  2189. horizontal_header.resizeSection(5, 17)
  2190. self.ui.tools_table.setColumnWidth(5, 17)
  2191. # horizontal_header.setStretchLastSection(True)
  2192. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2193. # horizontal_header.setStretchLastSection(True)
  2194. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2195. self.ui.tools_table.setSortingEnabled(False)
  2196. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  2197. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  2198. if not self.drills:
  2199. self.ui.tdlabel.hide()
  2200. self.ui.tooldia_entry.hide()
  2201. self.ui.generate_milling_button.hide()
  2202. else:
  2203. self.ui.tdlabel.show()
  2204. self.ui.tooldia_entry.show()
  2205. self.ui.generate_milling_button.show()
  2206. if not self.slots:
  2207. self.ui.stdlabel.hide()
  2208. self.ui.slot_tooldia_entry.hide()
  2209. self.ui.generate_milling_slots_button.hide()
  2210. else:
  2211. self.ui.stdlabel.show()
  2212. self.ui.slot_tooldia_entry.show()
  2213. self.ui.generate_milling_slots_button.show()
  2214. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  2215. for row in range(self.ui.tools_table.rowCount()):
  2216. try:
  2217. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2218. offset_spin_widget.valueChanged.connect(self.on_tool_offset_edit)
  2219. except (TypeError, AttributeError):
  2220. pass
  2221. self.ui_connect()
  2222. def set_ui(self, ui):
  2223. """
  2224. Configures the user interface for this object.
  2225. Connects options to form fields.
  2226. :param ui: User interface object.
  2227. :type ui: ExcellonObjectUI
  2228. :return: None
  2229. """
  2230. FlatCAMObj.set_ui(self, ui)
  2231. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  2232. self.units = self.app.defaults['units'].upper()
  2233. self.form_fields.update({
  2234. "plot": self.ui.plot_cb,
  2235. "solid": self.ui.solid_cb,
  2236. "drillz": self.ui.cutz_entry,
  2237. "travelz": self.ui.travelz_entry,
  2238. "feedrate": self.ui.feedrate_entry,
  2239. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  2240. "tooldia": self.ui.tooldia_entry,
  2241. "slot_tooldia": self.ui.slot_tooldia_entry,
  2242. "toolchange": self.ui.toolchange_cb,
  2243. "toolchangez": self.ui.toolchangez_entry,
  2244. "spindlespeed": self.ui.spindlespeed_entry,
  2245. "dwell": self.ui.dwell_cb,
  2246. "dwelltime": self.ui.dwelltime_entry,
  2247. "startz": self.ui.estartz_entry,
  2248. "endz": self.ui.eendz_entry,
  2249. "ppname_e": self.ui.pp_excellon_name_cb,
  2250. "z_pdepth": self.ui.pdepth_entry,
  2251. "feedrate_probe": self.ui.feedrate_probe_entry,
  2252. "gcode_type": self.ui.excellon_gcode_type_radio
  2253. })
  2254. for name in list(self.app.preprocessors.keys()):
  2255. # the HPGL preprocessor is only for Geometry not for Excellon job therefore don't add it
  2256. if name == 'hpgl':
  2257. continue
  2258. self.ui.pp_excellon_name_cb.addItem(name)
  2259. # Fill form fields
  2260. self.to_form()
  2261. # update the changes in UI depending on the selected preprocessor in Preferences
  2262. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  2263. # self.ui.pp_excellon_name_cb combobox
  2264. self.on_pp_changed()
  2265. # initialize the dict that holds the tools offset
  2266. t_default_offset = self.app.defaults["excellon_offset"]
  2267. if not self.tool_offset:
  2268. for value in self.tools.values():
  2269. dia = float('%.*f' % (self.decimals, float(value['C'])))
  2270. self.tool_offset[dia] = t_default_offset
  2271. # Show/Hide Advanced Options
  2272. if self.app.defaults["global_app_level"] == 'b':
  2273. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  2274. self.ui.tools_table.setColumnHidden(4, True)
  2275. self.ui.estartz_label.hide()
  2276. self.ui.estartz_entry.hide()
  2277. self.ui.feedrate_rapid_label.hide()
  2278. self.ui.feedrate_rapid_entry.hide()
  2279. self.ui.pdepth_label.hide()
  2280. self.ui.pdepth_entry.hide()
  2281. self.ui.feedrate_probe_label.hide()
  2282. self.ui.feedrate_probe_entry.hide()
  2283. else:
  2284. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  2285. assert isinstance(self.ui, ExcellonObjectUI), \
  2286. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  2287. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2288. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  2289. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  2290. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  2291. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  2292. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  2293. self.units_found = self.app.defaults['units']
  2294. def ui_connect(self):
  2295. for row in range(self.ui.tools_table.rowCount() - 2):
  2296. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  2297. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2298. def ui_disconnect(self):
  2299. for row in range(self.ui.tools_table.rowCount()):
  2300. try:
  2301. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  2302. except (TypeError, AttributeError):
  2303. pass
  2304. try:
  2305. self.ui.plot_cb.stateChanged.disconnect()
  2306. except (TypeError, AttributeError):
  2307. pass
  2308. def on_tool_offset_edit(self):
  2309. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2310. for row in range(self.ui.tools_table.rowCount()):
  2311. try:
  2312. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  2313. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2314. offset_spin_widget.valueChanged.disconnect()
  2315. except (TypeError, AttributeError):
  2316. pass
  2317. self.units = self.app.defaults['units'].upper()
  2318. self.is_modified = True
  2319. row_of_item_changed = self.ui.tools_table.currentRow()
  2320. dia = float('%.*f' % (self.decimals, float(self.ui.tools_table.item(row_of_item_changed, 1).text())))
  2321. self.tool_offset[dia] = self.sender().get_value()
  2322. # we reactivate the signals after the after the tool editing
  2323. for row in range(self.ui.tools_table.rowCount()):
  2324. try:
  2325. offset_spin_widget = self.ui.tools_table.cellWidget(row, 4)
  2326. offset_spin_widget.valueChanged.connect(self.on_tool_offset_edit)
  2327. except (TypeError, AttributeError):
  2328. pass
  2329. def get_selected_tools_list(self):
  2330. """
  2331. Returns the keys to the self.tools dictionary corresponding
  2332. to the selections on the tool list in the GUI.
  2333. :return: List of tools.
  2334. :rtype: list
  2335. """
  2336. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  2337. def get_selected_tools_table_items(self):
  2338. """
  2339. Returns a list of lists, each list in the list is made out of row elements
  2340. :return: List of table_tools items.
  2341. :rtype: list
  2342. """
  2343. table_tools_items = []
  2344. for x in self.ui.tools_table.selectedItems():
  2345. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  2346. # which does not have text
  2347. txt = ''
  2348. elem = list()
  2349. for column in range(0, self.ui.tools_table.columnCount() - 1):
  2350. try:
  2351. txt = self.ui.tools_table.item(x.row(), column).text()
  2352. except AttributeError:
  2353. try:
  2354. txt = self.ui.tools_table.cellWidget(x.row(), column).currentText()
  2355. except AttributeError:
  2356. pass
  2357. elem.append(txt)
  2358. table_tools_items.append(deepcopy(elem))
  2359. # table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  2360. # for column in range(0, self.ui.tools_table.columnCount() - 1)])
  2361. for item in table_tools_items:
  2362. item[0] = str(item[0])
  2363. return table_tools_items
  2364. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1, slot_type='routing'):
  2365. """
  2366. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  2367. :return: has_slots and Excellon_code
  2368. """
  2369. excellon_code = ''
  2370. # store here if the file has slots, return 1 if any slots, 0 if only drills
  2371. has_slots = 0
  2372. # drills processing
  2373. try:
  2374. if self.drills:
  2375. length = whole + fract
  2376. for tool in self.tools:
  2377. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  2378. for drill in self.drills:
  2379. if form == 'dec' and tool == drill['tool']:
  2380. drill_x = drill['point'].x * factor
  2381. drill_y = drill['point'].y * factor
  2382. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  2383. elif e_zeros == 'LZ' and tool == drill['tool']:
  2384. drill_x = drill['point'].x * factor
  2385. drill_y = drill['point'].y * factor
  2386. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  2387. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  2388. # extract whole part and decimal part
  2389. exc_x_formatted = exc_x_formatted.partition('.')
  2390. exc_y_formatted = exc_y_formatted.partition('.')
  2391. # left padd the 'whole' part with zeros
  2392. x_whole = exc_x_formatted[0].rjust(whole, '0')
  2393. y_whole = exc_y_formatted[0].rjust(whole, '0')
  2394. # restore the coordinate padded in the left with 0 and added the decimal part
  2395. # without the decinal dot
  2396. exc_x_formatted = x_whole + exc_x_formatted[2]
  2397. exc_y_formatted = y_whole + exc_y_formatted[2]
  2398. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  2399. yform=exc_y_formatted)
  2400. elif tool == drill['tool']:
  2401. drill_x = drill['point'].x * factor
  2402. drill_y = drill['point'].y * factor
  2403. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  2404. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  2405. # pad with rear zeros
  2406. exc_x_formatted.ljust(length, '0')
  2407. exc_y_formatted.ljust(length, '0')
  2408. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  2409. yform=exc_y_formatted)
  2410. except Exception as e:
  2411. log.debug(str(e))
  2412. # slots processing
  2413. try:
  2414. if self.slots:
  2415. has_slots = 1
  2416. for tool in self.tools:
  2417. excellon_code += 'G05\n'
  2418. if int(tool) < 10:
  2419. excellon_code += 'T0' + str(tool) + '\n'
  2420. else:
  2421. excellon_code += 'T' + str(tool) + '\n'
  2422. for slot in self.slots:
  2423. if form == 'dec' and tool == slot['tool']:
  2424. start_slot_x = slot['start'].x * factor
  2425. start_slot_y = slot['start'].y * factor
  2426. stop_slot_x = slot['stop'].x * factor
  2427. stop_slot_y = slot['stop'].y * factor
  2428. if slot_type == 'routing':
  2429. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  2430. start_slot_y,
  2431. dec=fract)
  2432. excellon_code += "G01X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  2433. stop_slot_y,
  2434. dec=fract)
  2435. elif slot_type == 'drilling':
  2436. excellon_code += "X{:.{dec}f}Y{:.{dec}f}G85X{:.{dec}f}Y{:.{dec}f}\nG05\n".format(
  2437. start_slot_x, start_slot_y, stop_slot_x, stop_slot_y, dec=fract
  2438. )
  2439. elif e_zeros == 'LZ' and tool == slot['tool']:
  2440. start_slot_x = slot['start'].x * factor
  2441. start_slot_y = slot['start'].y * factor
  2442. stop_slot_x = slot['stop'].x * factor
  2443. stop_slot_y = slot['stop'].y * factor
  2444. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  2445. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  2446. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  2447. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  2448. # extract whole part and decimal part
  2449. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  2450. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  2451. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  2452. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  2453. # left padd the 'whole' part with zeros
  2454. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  2455. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  2456. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  2457. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  2458. # restore the coordinate padded in the left with 0 and added the decimal part
  2459. # without the decinal dot
  2460. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  2461. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  2462. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  2463. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  2464. if slot_type == 'routing':
  2465. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  2466. ystart=start_slot_y_formatted)
  2467. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  2468. ystop=stop_slot_y_formatted)
  2469. elif slot_type == 'drilling':
  2470. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  2471. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  2472. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  2473. )
  2474. elif tool == slot['tool']:
  2475. start_slot_x = slot['start'].x * factor
  2476. start_slot_y = slot['start'].y * factor
  2477. stop_slot_x = slot['stop'].x * factor
  2478. stop_slot_y = slot['stop'].y * factor
  2479. length = whole + fract
  2480. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  2481. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  2482. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  2483. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  2484. # pad with rear zeros
  2485. start_slot_x_formatted.ljust(length, '0')
  2486. start_slot_y_formatted.ljust(length, '0')
  2487. stop_slot_x_formatted.ljust(length, '0')
  2488. stop_slot_y_formatted.ljust(length, '0')
  2489. if slot_type == 'routing':
  2490. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  2491. ystart=start_slot_y_formatted)
  2492. excellon_code += "G01X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  2493. ystop=stop_slot_y_formatted)
  2494. elif slot_type == 'drilling':
  2495. excellon_code += "{xstart}Y{ystart}G85X{xstop}Y{ystop}\nG05\n".format(
  2496. xstart=start_slot_x_formatted, ystart=start_slot_y_formatted,
  2497. xstop=stop_slot_x_formatted, ystop=stop_slot_y_formatted
  2498. )
  2499. except Exception as e:
  2500. log.debug(str(e))
  2501. if not self.drills and not self.slots:
  2502. log.debug("FlatCAMObj.FlatCAMExcellon.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  2503. return 'fail'
  2504. return has_slots, excellon_code
  2505. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  2506. """
  2507. Note: This method is a good template for generic operations as
  2508. it takes it's options from parameters or otherwise from the
  2509. object's options and returns a (success, msg) tuple as feedback
  2510. for shell operations.
  2511. :return: Success/failure condition tuple (bool, str).
  2512. :rtype: tuple
  2513. """
  2514. # Get the tools from the list. These are keys
  2515. # to self.tools
  2516. if tools is None:
  2517. tools = self.get_selected_tools_list()
  2518. if outname is None:
  2519. outname = self.options["name"] + "_mill"
  2520. if tooldia is None:
  2521. tooldia = float(self.options["tooldia"])
  2522. # Sort tools by diameter. items() -> [('name', diameter), ...]
  2523. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  2524. sort = []
  2525. for k, v in self.tools.items():
  2526. sort.append((k, v.get('C')))
  2527. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2528. if tools == "all":
  2529. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  2530. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  2531. if len(tools) == 0:
  2532. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2533. _("Please select one or more tools from the list and try again."))
  2534. return False, "Error: No tools."
  2535. for tool in tools:
  2536. if tooldia > self.tools[tool]["C"]:
  2537. self.app.inform.emit(
  2538. '[ERROR_NOTCL] %s %s: %s' % (
  2539. _("Milling tool for DRILLS is larger than hole size. Cancelled."),
  2540. _("Tool"),
  2541. str(tool)
  2542. )
  2543. )
  2544. return False, "Error: Milling tool is larger than hole."
  2545. def geo_init(geo_obj, app_obj):
  2546. assert isinstance(geo_obj, FlatCAMGeometry), \
  2547. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2548. app_obj.progress.emit(20)
  2549. # ## Add properties to the object
  2550. # get the tool_table items in a list of row items
  2551. tool_table_items = self.get_selected_tools_table_items()
  2552. # insert an information only element in the front
  2553. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2554. geo_obj.options['Tools_in_use'] = tool_table_items
  2555. geo_obj.options['type'] = 'Excellon Geometry'
  2556. geo_obj.options["cnctooldia"] = str(tooldia)
  2557. geo_obj.solid_geometry = []
  2558. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  2559. # for FlatCAM is 6 decimals,
  2560. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  2561. for hole in self.drills:
  2562. if hole['tool'] in tools:
  2563. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  2564. if buffer_value == 0:
  2565. geo_obj.solid_geometry.append(
  2566. Point(hole['point']).buffer(0.0000001).exterior)
  2567. else:
  2568. geo_obj.solid_geometry.append(
  2569. Point(hole['point']).buffer(buffer_value).exterior)
  2570. if use_thread:
  2571. def geo_thread(app_obj):
  2572. app_obj.new_object("geometry", outname, geo_init, plot=plot)
  2573. app_obj.progress.emit(100)
  2574. # Create a promise with the new name
  2575. self.app.collection.promise(outname)
  2576. # Send to worker
  2577. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  2578. else:
  2579. self.app.new_object("geometry", outname, geo_init, plot=plot)
  2580. return True, ""
  2581. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, plot=True, use_thread=False):
  2582. """
  2583. Note: This method is a good template for generic operations as
  2584. it takes it's options from parameters or otherwise from the
  2585. object's options and returns a (success, msg) tuple as feedback
  2586. for shell operations.
  2587. :return: Success/failure condition tuple (bool, str).
  2588. :rtype: tuple
  2589. """
  2590. # Get the tools from the list. These are keys
  2591. # to self.tools
  2592. if tools is None:
  2593. tools = self.get_selected_tools_list()
  2594. if outname is None:
  2595. outname = self.options["name"] + "_mill"
  2596. if tooldia is None:
  2597. tooldia = float(self.options["slot_tooldia"])
  2598. # Sort tools by diameter. items() -> [('name', diameter), ...]
  2599. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  2600. sort = []
  2601. for k, v in self.tools.items():
  2602. sort.append((k, v.get('C')))
  2603. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  2604. if tools == "all":
  2605. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  2606. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  2607. if len(tools) == 0:
  2608. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2609. _("Please select one or more tools from the list and try again."))
  2610. return False, "Error: No tools."
  2611. for tool in tools:
  2612. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  2613. adj_toolstable_tooldia = float('%.*f' % (self.decimals, float(tooldia)))
  2614. adj_file_tooldia = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  2615. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  2616. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2617. _("Milling tool for SLOTS is larger than hole size. Cancelled."))
  2618. return False, "Error: Milling tool is larger than hole."
  2619. def geo_init(geo_obj, app_obj):
  2620. assert isinstance(geo_obj, FlatCAMGeometry), \
  2621. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2622. app_obj.progress.emit(20)
  2623. # ## Add properties to the object
  2624. # get the tool_table items in a list of row items
  2625. tool_table_items = self.get_selected_tools_table_items()
  2626. # insert an information only element in the front
  2627. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2628. geo_obj.options['Tools_in_use'] = tool_table_items
  2629. geo_obj.options['type'] = 'Excellon Geometry'
  2630. geo_obj.options["cnctooldia"] = str(tooldia)
  2631. geo_obj.solid_geometry = []
  2632. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  2633. # for FlatCAM is 6 decimals,
  2634. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  2635. for slot in self.slots:
  2636. if slot['tool'] in tools:
  2637. toolstable_tool = float('%.*f' % (self.decimals, float(tooldia)))
  2638. file_tool = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  2639. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  2640. # for the file_tool (tooldia actually)
  2641. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  2642. if buffer_value == 0:
  2643. start = slot['start']
  2644. stop = slot['stop']
  2645. lines_string = LineString([start, stop])
  2646. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  2647. geo_obj.solid_geometry.append(poly)
  2648. else:
  2649. start = slot['start']
  2650. stop = slot['stop']
  2651. lines_string = LineString([start, stop])
  2652. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  2653. geo_obj.solid_geometry.append(poly)
  2654. if use_thread:
  2655. def geo_thread(app_obj):
  2656. app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  2657. app_obj.progress.emit(100)
  2658. # Create a promise with the new name
  2659. self.app.collection.promise(outname)
  2660. # Send to worker
  2661. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  2662. else:
  2663. self.app.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  2664. return True, ""
  2665. def on_generate_milling_button_click(self, *args):
  2666. self.app.report_usage("excellon_on_create_milling_drills button")
  2667. self.read_form()
  2668. self.generate_milling_drills(use_thread=False)
  2669. def on_generate_milling_slots_button_click(self, *args):
  2670. self.app.report_usage("excellon_on_create_milling_slots_button")
  2671. self.read_form()
  2672. self.generate_milling_slots(use_thread=False)
  2673. def on_pp_changed(self):
  2674. current_pp = self.ui.pp_excellon_name_cb.get_value()
  2675. if "toolchange_probe" in current_pp.lower():
  2676. self.ui.pdepth_entry.setVisible(True)
  2677. self.ui.pdepth_label.show()
  2678. self.ui.feedrate_probe_entry.setVisible(True)
  2679. self.ui.feedrate_probe_label.show()
  2680. else:
  2681. self.ui.pdepth_entry.setVisible(False)
  2682. self.ui.pdepth_label.hide()
  2683. self.ui.feedrate_probe_entry.setVisible(False)
  2684. self.ui.feedrate_probe_label.hide()
  2685. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  2686. self.ui.feedrate_rapid_label.show()
  2687. self.ui.feedrate_rapid_entry.show()
  2688. else:
  2689. self.ui.feedrate_rapid_label.hide()
  2690. self.ui.feedrate_rapid_entry.hide()
  2691. def on_create_cncjob_button_click(self, *args):
  2692. self.app.report_usage("excellon_on_create_cncjob_button")
  2693. self.read_form()
  2694. # Get the tools from the list
  2695. tools = self.get_selected_tools_list()
  2696. if len(tools) == 0:
  2697. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  2698. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  2699. # in this case regardless of the selection status of that tool, use it.
  2700. if self.ui.tools_table.rowCount() == 3:
  2701. tools.append(self.ui.tools_table.item(0, 0).text())
  2702. else:
  2703. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2704. _("Please select one or more tools from the list and try again."))
  2705. return
  2706. xmin = self.options['xmin']
  2707. ymin = self.options['ymin']
  2708. xmax = self.options['xmax']
  2709. ymax = self.options['ymax']
  2710. job_name = self.options["name"] + "_cnc"
  2711. pp_excellon_name = self.options["ppname_e"]
  2712. # Object initialization function for app.new_object()
  2713. def job_init(job_obj, app_obj):
  2714. assert isinstance(job_obj, FlatCAMCNCjob), \
  2715. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2716. # get the tool_table items in a list of row items
  2717. tool_table_items = self.get_selected_tools_table_items()
  2718. # insert an information only element in the front
  2719. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  2720. # ## Add properties to the object
  2721. job_obj.origin_kind = 'excellon'
  2722. job_obj.options['Tools_in_use'] = tool_table_items
  2723. job_obj.options['type'] = 'Excellon'
  2724. job_obj.options['ppname_e'] = pp_excellon_name
  2725. app_obj.progress.emit(20)
  2726. job_obj.z_cut = float(self.options["drillz"])
  2727. job_obj.tool_offset = self.tool_offset
  2728. job_obj.z_move = float(self.options["travelz"])
  2729. job_obj.feedrate = float(self.options["feedrate"])
  2730. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  2731. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] != 0 else None
  2732. job_obj.spindledir = self.app.defaults['excellon_spindledir']
  2733. job_obj.dwell = self.options["dwell"]
  2734. job_obj.dwelltime = float(self.options["dwelltime"])
  2735. job_obj.pp_excellon_name = pp_excellon_name
  2736. job_obj.toolchange_xy_type = "excellon"
  2737. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  2738. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  2739. job_obj.options['xmin'] = xmin
  2740. job_obj.options['ymin'] = ymin
  2741. job_obj.options['xmax'] = xmax
  2742. job_obj.options['ymax'] = ymax
  2743. try:
  2744. job_obj.z_pdepth = float(self.options["z_pdepth"])
  2745. except ValueError:
  2746. # try to convert comma to decimal point. if it's still not working error message and return
  2747. try:
  2748. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  2749. except ValueError:
  2750. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2751. _('Wrong value format for self.defaults["z_pdepth"] '
  2752. 'or self.options["z_pdepth"]'))
  2753. try:
  2754. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  2755. except ValueError:
  2756. # try to convert comma to decimal point. if it's still not working error message and return
  2757. try:
  2758. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  2759. except ValueError:
  2760. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2761. _('Wrong value format for self.defaults["feedrate_probe"] or '
  2762. 'self.options["feedrate_probe"]'))
  2763. # There could be more than one drill size...
  2764. # job_obj.tooldia = # TODO: duplicate variable!
  2765. # job_obj.options["tooldia"] =
  2766. tools_csv = ','.join(tools)
  2767. ret_val = job_obj.generate_from_excellon_by_tool(
  2768. self, tools_csv,
  2769. drillz=float(self.options['drillz']),
  2770. toolchange=self.options["toolchange"],
  2771. toolchangexy=self.app.defaults["excellon_toolchangexy"],
  2772. toolchangez=float(self.options["toolchangez"]),
  2773. startz=float(self.options["startz"]) if self.options["startz"] else None,
  2774. endz=float(self.options["endz"]),
  2775. excellon_optimization_type=self.app.defaults["excellon_optimization_type"])
  2776. if ret_val == 'fail':
  2777. return 'fail'
  2778. app_obj.progress.emit(50)
  2779. job_obj.gcode_parse()
  2780. app_obj.progress.emit(60)
  2781. job_obj.create_geometry()
  2782. app_obj.progress.emit(80)
  2783. # To be run in separate thread
  2784. def job_thread(app_obj):
  2785. with self.app.proc_container.new(_("Generating CNC Code")):
  2786. app_obj.new_object("cncjob", job_name, job_init)
  2787. app_obj.progress.emit(100)
  2788. # Create promise for the new name.
  2789. self.app.collection.promise(job_name)
  2790. # Send to worker
  2791. # self.app.worker.add_task(job_thread, [self.app])
  2792. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2793. def convert_units(self, units):
  2794. log.debug("FlatCAMObj.FlatCAMExcellon.convert_units()")
  2795. Excellon.convert_units(self, units)
  2796. # factor = Excellon.convert_units(self, units)
  2797. # self.options['drillz'] = float(self.options['drillz']) * factor
  2798. # self.options['travelz'] = float(self.options['travelz']) * factor
  2799. # self.options['feedrate'] = float(self.options['feedrate']) * factor
  2800. # self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  2801. # self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  2802. #
  2803. # if self.app.defaults["excellon_toolchangexy"] == '':
  2804. # self.options['toolchangexy'] = "0.0, 0.0"
  2805. # else:
  2806. # coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  2807. # if len(coords_xy) < 2:
  2808. # self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2809. # "in the format (x, y) \n"
  2810. # "but now there is only one value, not two. "))
  2811. # return 'fail'
  2812. # coords_xy[0] *= factor
  2813. # coords_xy[1] *= factor
  2814. # self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2815. #
  2816. # if self.options['startz'] is not None:
  2817. # self.options['startz'] = float(self.options['startz']) * factor
  2818. # self.options['endz'] = float(self.options['endz']) * factor
  2819. def on_solid_cb_click(self, *args):
  2820. if self.muted_ui:
  2821. return
  2822. self.read_form_item('solid')
  2823. self.plot()
  2824. def on_plot_cb_click(self, *args):
  2825. if self.muted_ui:
  2826. return
  2827. self.plot()
  2828. self.read_form_item('plot')
  2829. self.ui_disconnect()
  2830. cb_flag = self.ui.plot_cb.isChecked()
  2831. for row in range(self.ui.tools_table.rowCount() - 2):
  2832. table_cb = self.ui.tools_table.cellWidget(row, 5)
  2833. if cb_flag:
  2834. table_cb.setChecked(True)
  2835. else:
  2836. table_cb.setChecked(False)
  2837. self.ui_connect()
  2838. def on_plot_cb_click_table(self):
  2839. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  2840. self.ui_disconnect()
  2841. # cw = self.sender()
  2842. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  2843. # cw_row = cw_index.row()
  2844. check_row = 0
  2845. self.shapes.clear(update=True)
  2846. for tool_key in self.tools:
  2847. solid_geometry = self.tools[tool_key]['solid_geometry']
  2848. # find the geo_tool_table row associated with the tool_key
  2849. for row in range(self.ui.tools_table.rowCount()):
  2850. tool_item = int(self.ui.tools_table.item(row, 0).text())
  2851. if tool_item == int(tool_key):
  2852. check_row = row
  2853. break
  2854. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  2855. self.options['plot'] = True
  2856. # self.plot_element(element=solid_geometry, visible=True)
  2857. # Plot excellon (All polygons?)
  2858. if self.options["solid"]:
  2859. for geo in solid_geometry:
  2860. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2861. visible=self.options['plot'],
  2862. layer=2)
  2863. else:
  2864. for geo in solid_geometry:
  2865. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2866. for ints in geo.interiors:
  2867. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  2868. self.shapes.redraw()
  2869. # make sure that the general plot is disabled if one of the row plot's are disabled and
  2870. # if all the row plot's are enabled also enable the general plot checkbox
  2871. cb_cnt = 0
  2872. total_row = self.ui.tools_table.rowCount()
  2873. for row in range(total_row - 2):
  2874. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  2875. cb_cnt += 1
  2876. else:
  2877. cb_cnt -= 1
  2878. if cb_cnt < total_row - 2:
  2879. self.ui.plot_cb.setChecked(False)
  2880. else:
  2881. self.ui.plot_cb.setChecked(True)
  2882. self.ui_connect()
  2883. # def plot_element(self, element, color='red', visible=None, layer=None):
  2884. #
  2885. # visible = visible if visible else self.options['plot']
  2886. #
  2887. # try:
  2888. # for sub_el in element:
  2889. # self.plot_element(sub_el)
  2890. #
  2891. # except TypeError: # Element is not iterable...
  2892. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2893. def plot(self, visible=None, kind=None):
  2894. # Does all the required setup and returns False
  2895. # if the 'ptint' option is set to False.
  2896. if not FlatCAMObj.plot(self):
  2897. return
  2898. # try:
  2899. # # Plot Excellon (All polygons?)
  2900. # if self.options["solid"]:
  2901. # for tool in self.tools:
  2902. # for geo in self.tools[tool]['solid_geometry']:
  2903. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2904. # visible=self.options['plot'],
  2905. # layer=2)
  2906. # else:
  2907. # for tool in self.tools:
  2908. # for geo in self.tools[tool]['solid_geometry']:
  2909. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  2910. # for ints in geo.interiors:
  2911. # self.add_shape(shape=ints, color='orange', visible=self.options['plot'])
  2912. #
  2913. # self.shapes.redraw()
  2914. # return
  2915. # except (ObjectDeleted, AttributeError, KeyError):
  2916. # self.shapes.clear(update=True)
  2917. # this stays for compatibility reasons, in case we try to open old projects
  2918. try:
  2919. __ = iter(self.solid_geometry)
  2920. except TypeError:
  2921. self.solid_geometry = [self.solid_geometry]
  2922. visible = visible if visible else self.options['plot']
  2923. try:
  2924. # Plot Excellon (All polygons?)
  2925. if self.options["solid"]:
  2926. for geo in self.solid_geometry:
  2927. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  2928. visible=visible,
  2929. layer=2)
  2930. else:
  2931. for geo in self.solid_geometry:
  2932. self.add_shape(shape=geo.exterior, color='red', visible=visible)
  2933. for ints in geo.interiors:
  2934. self.add_shape(shape=ints, color='orange', visible=visible)
  2935. self.shapes.redraw()
  2936. except (ObjectDeleted, AttributeError):
  2937. self.shapes.clear(update=True)
  2938. class FlatCAMGeometry(FlatCAMObj, Geometry):
  2939. """
  2940. Geometric object not associated with a specific
  2941. format.
  2942. """
  2943. optionChanged = QtCore.pyqtSignal(str)
  2944. ui_type = GeometryObjectUI
  2945. def __init__(self, name):
  2946. self.decimals = self.app.decimals
  2947. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  2948. FlatCAMObj.__init__(self, name)
  2949. Geometry.__init__(self, geo_steps_per_circle=self.circle_steps)
  2950. self.kind = "geometry"
  2951. self.options.update({
  2952. "plot": True,
  2953. "cutz": -0.002,
  2954. "vtipdia": 0.1,
  2955. "vtipangle": 30,
  2956. "travelz": 0.1,
  2957. "feedrate": 5.0,
  2958. "feedrate_z": 5.0,
  2959. "feedrate_rapid": 5.0,
  2960. "spindlespeed": 0,
  2961. "dwell": True,
  2962. "dwelltime": 1000,
  2963. "multidepth": False,
  2964. "depthperpass": 0.002,
  2965. "extracut": False,
  2966. "extracut_length": 0.1,
  2967. "endz": 2.0,
  2968. "startz": None,
  2969. "toolchange": False,
  2970. "toolchangez": 1.0,
  2971. "toolchangexy": "0.0, 0.0",
  2972. "ppname_g": 'default',
  2973. "z_pdepth": -0.02,
  2974. "feedrate_probe": 3.0,
  2975. })
  2976. if "cnctooldia" not in self.options:
  2977. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  2978. self.options["startz"] = self.app.defaults["geometry_startz"]
  2979. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  2980. self.tooluid = 0
  2981. '''
  2982. self.tools = {}
  2983. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  2984. tool_id of the tools and the value is another dict that will hold the data under the following form:
  2985. {tooluid: {
  2986. 'tooldia': 1,
  2987. 'offset': 'Path',
  2988. 'offset_value': 0.0
  2989. 'type': 'Rough',
  2990. 'tool_type': 'C1',
  2991. 'data': self.default_tool_data
  2992. 'solid_geometry': []
  2993. }
  2994. }
  2995. '''
  2996. self.tools = {}
  2997. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  2998. # those elements are the ones used for generating GCode
  2999. self.sel_tools = {}
  3000. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  3001. self.type_item_options = [_("Iso"), _("Rough"), _("Finish")]
  3002. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  3003. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  3004. self.v_tool_type = None
  3005. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  3006. # the default value is False
  3007. self.multigeo = False
  3008. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  3009. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  3010. self.special_group = None
  3011. self.old_pp_state = self.app.defaults["geometry_multidepth"]
  3012. self.old_toolchangeg_state = self.app.defaults["geometry_toolchange"]
  3013. self.units_found = self.app.defaults['units']
  3014. # this variable can be updated by the Object that generates the geometry
  3015. self.tool_type = 'C1'
  3016. # save here the old value for the Cut Z before it is changed by selecting a V-shape type tool in the tool table
  3017. self.old_cutz = self.app.defaults["geometry_cutz"]
  3018. # Attributes to be included in serialization
  3019. # Always append to it because it carries contents
  3020. # from predecessors.
  3021. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  3022. def build_ui(self):
  3023. self.ui_disconnect()
  3024. FlatCAMObj.build_ui(self)
  3025. self.units = self.app.defaults['units']
  3026. offset = 0
  3027. tool_idx = 0
  3028. n = len(self.tools)
  3029. self.ui.geo_tools_table.setRowCount(n)
  3030. for tooluid_key, tooluid_value in self.tools.items():
  3031. tool_idx += 1
  3032. row_no = tool_idx - 1
  3033. tool_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3034. tool_id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3035. self.ui.geo_tools_table.setItem(row_no, 0, tool_id) # Tool name/id
  3036. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3037. # There are no tool bits in MM with more than 3 decimals diameter.
  3038. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  3039. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooluid_value['tooldia'])))
  3040. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3041. offset_item = QtWidgets.QComboBox()
  3042. for item in self.offset_item_options:
  3043. offset_item.addItem(item)
  3044. # offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  3045. idx = offset_item.findText(tooluid_value['offset'])
  3046. offset_item.setCurrentIndex(idx)
  3047. type_item = QtWidgets.QComboBox()
  3048. for item in self.type_item_options:
  3049. type_item.addItem(item)
  3050. # type_item.setStyleSheet('background-color: rgb(255,255,255)')
  3051. idx = type_item.findText(tooluid_value['type'])
  3052. type_item.setCurrentIndex(idx)
  3053. tool_type_item = QtWidgets.QComboBox()
  3054. for item in self.tool_type_item_options:
  3055. tool_type_item.addItem(item)
  3056. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  3057. idx = tool_type_item.findText(tooluid_value['tool_type'])
  3058. tool_type_item.setCurrentIndex(idx)
  3059. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  3060. plot_item = FCCheckBox()
  3061. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3062. if self.ui.plot_cb.isChecked():
  3063. plot_item.setChecked(True)
  3064. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3065. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  3066. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  3067. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  3068. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3069. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  3070. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  3071. try:
  3072. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  3073. except Exception as e:
  3074. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools. Error: %s" % str(e))
  3075. # make the diameter column editable
  3076. for row in range(tool_idx):
  3077. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  3078. QtCore.Qt.ItemIsEditable |
  3079. QtCore.Qt.ItemIsEnabled)
  3080. # sort the tool diameter column
  3081. # self.ui.geo_tools_table.sortItems(1)
  3082. # all the tools are selected by default
  3083. # self.ui.geo_tools_table.selectColumn(0)
  3084. self.ui.geo_tools_table.resizeColumnsToContents()
  3085. self.ui.geo_tools_table.resizeRowsToContents()
  3086. vertical_header = self.ui.geo_tools_table.verticalHeader()
  3087. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  3088. vertical_header.hide()
  3089. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3090. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  3091. horizontal_header.setMinimumSectionSize(10)
  3092. horizontal_header.setDefaultSectionSize(70)
  3093. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  3094. horizontal_header.resizeSection(0, 20)
  3095. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  3096. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  3097. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  3098. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  3099. horizontal_header.resizeSection(4, 40)
  3100. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  3101. horizontal_header.resizeSection(4, 17)
  3102. # horizontal_header.setStretchLastSection(True)
  3103. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3104. self.ui.geo_tools_table.setColumnWidth(0, 20)
  3105. self.ui.geo_tools_table.setColumnWidth(4, 40)
  3106. self.ui.geo_tools_table.setColumnWidth(6, 17)
  3107. # self.ui.geo_tools_table.setSortingEnabled(True)
  3108. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  3109. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  3110. # update UI for all rows - useful after units conversion but only if there is at least one row
  3111. row_cnt = self.ui.geo_tools_table.rowCount()
  3112. if row_cnt > 0:
  3113. for r in range(row_cnt):
  3114. self.update_ui(r)
  3115. # select only the first tool / row
  3116. selected_row = 0
  3117. try:
  3118. self.select_tools_table_row(selected_row, clearsel=True)
  3119. # update the Geometry UI
  3120. self.update_ui()
  3121. except Exception as e:
  3122. # when the tools table is empty there will be this error but once the table is populated it will go away
  3123. log.debug(str(e))
  3124. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  3125. # and can create some problems
  3126. if self.multigeo is False:
  3127. self.ui.geo_tools_table.setColumnHidden(6, True)
  3128. else:
  3129. self.ui.geo_tools_table.setColumnHidden(6, False)
  3130. self.set_tool_offset_visibility(selected_row)
  3131. # HACK: for whatever reasons the name in Selected tab is reverted to the original one after a successful rename
  3132. # done in the collection view but only for Geometry objects. Perhaps some references remains. Should be fixed.
  3133. self.ui.name_entry.set_value(self.options['name'])
  3134. self.ui_connect()
  3135. self.ui.e_cut_entry.setDisabled(False) if self.ui.extracut_cb.get_value() else \
  3136. self.ui.e_cut_entry.setDisabled(True)
  3137. def set_ui(self, ui):
  3138. FlatCAMObj.set_ui(self, ui)
  3139. log.debug("FlatCAMGeometry.set_ui()")
  3140. assert isinstance(self.ui, GeometryObjectUI), \
  3141. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  3142. self.units = self.app.defaults['units'].upper()
  3143. self.units_found = self.app.defaults['units']
  3144. # populate preprocessor names in the combobox
  3145. for name in list(self.app.preprocessors.keys()):
  3146. self.ui.pp_geometry_name_cb.addItem(name)
  3147. self.form_fields.update({
  3148. "plot": self.ui.plot_cb,
  3149. "cutz": self.ui.cutz_entry,
  3150. "vtipdia": self.ui.tipdia_entry,
  3151. "vtipangle": self.ui.tipangle_entry,
  3152. "travelz": self.ui.travelz_entry,
  3153. "feedrate": self.ui.cncfeedrate_entry,
  3154. "feedrate_z": self.ui.cncplunge_entry,
  3155. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  3156. "spindlespeed": self.ui.cncspindlespeed_entry,
  3157. "dwell": self.ui.dwell_cb,
  3158. "dwelltime": self.ui.dwelltime_entry,
  3159. "multidepth": self.ui.mpass_cb,
  3160. "ppname_g": self.ui.pp_geometry_name_cb,
  3161. "z_pdepth": self.ui.pdepth_entry,
  3162. "feedrate_probe": self.ui.feedrate_probe_entry,
  3163. "depthperpass": self.ui.maxdepth_entry,
  3164. "extracut": self.ui.extracut_cb,
  3165. "extracut_length": self.ui.e_cut_entry,
  3166. "toolchange": self.ui.toolchangeg_cb,
  3167. "toolchangez": self.ui.toolchangez_entry,
  3168. "endz": self.ui.gendz_entry,
  3169. "cnctooldia": self.ui.addtool_entry
  3170. })
  3171. # Fill form fields only on object create
  3172. self.to_form()
  3173. # update the changes in UI depending on the selected preprocessor in Preferences
  3174. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  3175. # self.ui.pp_geometry_name_cb combobox
  3176. self.on_pp_changed()
  3177. self.ui.tipdialabel.hide()
  3178. self.ui.tipdia_entry.hide()
  3179. self.ui.tipanglelabel.hide()
  3180. self.ui.tipangle_entry.hide()
  3181. self.ui.cutz_entry.setDisabled(False)
  3182. # store here the default data for Geometry Data
  3183. self.default_data = dict()
  3184. self.default_data.update({
  3185. "name": None,
  3186. "plot": None,
  3187. "cutz": None,
  3188. "vtipdia": None,
  3189. "vtipangle": None,
  3190. "travelz": None,
  3191. "feedrate": None,
  3192. "feedrate_z": None,
  3193. "feedrate_rapid": None,
  3194. "dwell": None,
  3195. "dwelltime": None,
  3196. "multidepth": None,
  3197. "ppname_g": None,
  3198. "depthperpass": None,
  3199. "extracut": None,
  3200. "extracut_length": None,
  3201. "toolchange": None,
  3202. "toolchangez": None,
  3203. "endz": None,
  3204. "spindlespeed": 0,
  3205. "toolchangexy": None,
  3206. "startz": None
  3207. })
  3208. # fill in self.default_data values from self.options
  3209. for def_key in self.default_data:
  3210. for opt_key, opt_val in self.options.items():
  3211. if def_key == opt_key:
  3212. self.default_data[def_key] = deepcopy(opt_val)
  3213. try:
  3214. temp_tools = self.options["cnctooldia"].split(",")
  3215. tools_list = [
  3216. float(eval(dia)) for dia in temp_tools if dia != ''
  3217. ]
  3218. except Exception as e:
  3219. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> Geometry General -> "
  3220. "Tool dia. %s" % str(e))
  3221. return
  3222. self.tooluid += 1
  3223. if not self.tools:
  3224. for toold in tools_list:
  3225. new_data = deepcopy(self.default_data)
  3226. self.tools.update({
  3227. self.tooluid: {
  3228. 'tooldia': float('%.*f' % (self.decimals, float(toold))),
  3229. 'offset': 'Path',
  3230. 'offset_value': 0.0,
  3231. 'type': _('Rough'),
  3232. 'tool_type': self.tool_type,
  3233. 'data': new_data,
  3234. 'solid_geometry': self.solid_geometry
  3235. }
  3236. })
  3237. self.tooluid += 1
  3238. else:
  3239. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  3240. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  3241. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  3242. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  3243. # following convoluted way of changing the keys from string to float type
  3244. temp_tools = {}
  3245. for tooluid_key in self.tools:
  3246. val = deepcopy(self.tools[tooluid_key])
  3247. new_key = deepcopy(int(tooluid_key))
  3248. temp_tools[new_key] = val
  3249. self.tools.clear()
  3250. self.tools = deepcopy(temp_tools)
  3251. self.ui.tool_offset_entry.hide()
  3252. self.ui.tool_offset_lbl.hide()
  3253. # used to store the state of the mpass_cb if the selected preprocessor for geometry is hpgl
  3254. self.old_pp_state = self.default_data['multidepth']
  3255. self.old_toolchangeg_state = self.default_data['toolchange']
  3256. if not isinstance(self.ui, GeometryObjectUI):
  3257. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  3258. return
  3259. self.ui.geo_tools_table.setupContextMenu()
  3260. self.ui.geo_tools_table.addContextMenu(
  3261. _("Add from Tool DB"), self.on_tool_add_from_db_clicked,
  3262. icon=QtGui.QIcon(self.app.resource_location + "/plus16.png"))
  3263. self.ui.geo_tools_table.addContextMenu(
  3264. _("Copy"), self.on_tool_copy,
  3265. icon=QtGui.QIcon(self.app.resource_location + "/copy16.png"))
  3266. self.ui.geo_tools_table.addContextMenu(
  3267. _("Delete"), lambda: self.on_tool_delete(all=None),
  3268. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png"))
  3269. # Show/Hide Advanced Options
  3270. if self.app.defaults["global_app_level"] == 'b':
  3271. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  3272. self.ui.geo_tools_table.setColumnHidden(2, True)
  3273. self.ui.geo_tools_table.setColumnHidden(3, True)
  3274. # self.ui.geo_tools_table.setColumnHidden(4, True)
  3275. self.ui.addtool_entry_lbl.hide()
  3276. self.ui.addtool_entry.hide()
  3277. self.ui.addtool_btn.hide()
  3278. self.ui.copytool_btn.hide()
  3279. self.ui.deltool_btn.hide()
  3280. # self.ui.endzlabel.hide()
  3281. # self.ui.gendz_entry.hide()
  3282. self.ui.fr_rapidlabel.hide()
  3283. self.ui.cncfeedrate_rapid_entry.hide()
  3284. self.ui.extracut_cb.hide()
  3285. self.ui.e_cut_entry.hide()
  3286. self.ui.pdepth_label.hide()
  3287. self.ui.pdepth_entry.hide()
  3288. self.ui.feedrate_probe_label.hide()
  3289. self.ui.feedrate_probe_entry.hide()
  3290. else:
  3291. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  3292. self.ui.e_cut_entry.setDisabled(False) if self.app.defaults['geometry_extracut'] else \
  3293. self.ui.e_cut_entry.setDisabled(True)
  3294. self.ui.extracut_cb.toggled.connect(lambda state: self.ui.e_cut_entry.setDisabled(not state))
  3295. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3296. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  3297. self.ui.paint_tool_button.clicked.connect(lambda: self.app.paint_tool.run(toggle=False))
  3298. self.ui.generate_ncc_button.clicked.connect(lambda: self.app.ncclear_tool.run(toggle=False))
  3299. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  3300. self.ui.tipdia_entry.valueChanged.connect(self.update_cutz)
  3301. self.ui.tipangle_entry.valueChanged.connect(self.update_cutz)
  3302. self.ui.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  3303. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  3304. self.ui.cutz_entry.returnPressed.connect(self.on_cut_z_changed)
  3305. def on_cut_z_changed(self):
  3306. self.old_cutz = self.ui.cutz_entry.get_value()
  3307. def set_tool_offset_visibility(self, current_row):
  3308. if current_row is None:
  3309. return
  3310. try:
  3311. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  3312. if tool_offset is not None:
  3313. tool_offset_txt = tool_offset.currentText()
  3314. if tool_offset_txt == 'Custom':
  3315. self.ui.tool_offset_entry.show()
  3316. self.ui.tool_offset_lbl.show()
  3317. else:
  3318. self.ui.tool_offset_entry.hide()
  3319. self.ui.tool_offset_lbl.hide()
  3320. except Exception as e:
  3321. log.debug("set_tool_offset_visibility() --> " + str(e))
  3322. return
  3323. def on_offset_value_edited(self):
  3324. """
  3325. This will save the offset_value into self.tools storage whenever the offset value is edited
  3326. :return:
  3327. """
  3328. for current_row in self.ui.geo_tools_table.selectedItems():
  3329. # sometime the header get selected and it has row number -1
  3330. # we don't want to do anything with the header :)
  3331. if current_row.row() < 0:
  3332. continue
  3333. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3334. self.set_tool_offset_visibility(current_row.row())
  3335. for tooluid_key, tooluid_value in self.tools.items():
  3336. if int(tooluid_key) == tool_uid:
  3337. try:
  3338. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  3339. except ValueError:
  3340. # try to convert comma to decimal point. if it's still not working error message and return
  3341. try:
  3342. tooluid_value['offset_value'] = float(
  3343. self.ui.tool_offset_entry.get_value().replace(',', '.')
  3344. )
  3345. except ValueError:
  3346. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3347. _("Wrong value format entered, use a number."))
  3348. return
  3349. def ui_connect(self):
  3350. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  3351. # changes in geometry UI
  3352. for i in range(self.ui.grid3.count()):
  3353. current_widget = self.ui.grid3.itemAt(i).widget()
  3354. if isinstance(current_widget, FCCheckBox):
  3355. current_widget.stateChanged.connect(self.gui_form_to_storage)
  3356. elif isinstance(current_widget, FCComboBox):
  3357. current_widget.currentIndexChanged.connect(self.gui_form_to_storage)
  3358. elif isinstance(current_widget, FloatEntry) or isinstance(current_widget, LengthEntry) or \
  3359. isinstance(current_widget, FCEntry) or isinstance(current_widget, IntEntry):
  3360. current_widget.editingFinished.connect(self.gui_form_to_storage)
  3361. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  3362. current_widget.returnPressed.connect(self.gui_form_to_storage)
  3363. for row in range(self.ui.geo_tools_table.rowCount()):
  3364. for col in [2, 3, 4]:
  3365. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  3366. self.on_tooltable_cellwidget_change)
  3367. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  3368. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  3369. self.ui.addtool_entry.returnPressed.connect(self.on_tool_add)
  3370. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  3371. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  3372. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  3373. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  3374. self.ui.tool_offset_entry.returnPressed.connect(self.on_offset_value_edited)
  3375. for row in range(self.ui.geo_tools_table.rowCount()):
  3376. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  3377. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3378. def ui_disconnect(self):
  3379. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  3380. # changes in geometry UI
  3381. for i in range(self.ui.grid3.count()):
  3382. current_widget = self.ui.grid3.itemAt(i).widget()
  3383. if isinstance(current_widget, FCCheckBox):
  3384. try:
  3385. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect(self.gui_form_to_storage)
  3386. except (TypeError, AttributeError):
  3387. pass
  3388. elif isinstance(current_widget, FCComboBox):
  3389. try:
  3390. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect(self.gui_form_to_storage)
  3391. except (TypeError, AttributeError):
  3392. pass
  3393. elif isinstance(current_widget, LengthEntry) or isinstance(current_widget, IntEntry) or \
  3394. isinstance(current_widget, FCEntry) or isinstance(current_widget, FloatEntry):
  3395. try:
  3396. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect(self.gui_form_to_storage)
  3397. except (TypeError, AttributeError):
  3398. pass
  3399. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  3400. try:
  3401. self.ui.grid3.itemAt(i).widget().returnPressed.disconnect(self.gui_form_to_storage)
  3402. except TypeError:
  3403. pass
  3404. for row in range(self.ui.geo_tools_table.rowCount()):
  3405. for col in [2, 3, 4]:
  3406. try:
  3407. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  3408. except (TypeError, AttributeError):
  3409. pass
  3410. try:
  3411. self.ui.addtool_btn.clicked.disconnect()
  3412. except (TypeError, AttributeError):
  3413. pass
  3414. try:
  3415. self.ui.addtool_entry.returnPressed.disconnect()
  3416. except (TypeError, AttributeError):
  3417. pass
  3418. try:
  3419. self.ui.copytool_btn.clicked.disconnect()
  3420. except (TypeError, AttributeError):
  3421. pass
  3422. try:
  3423. self.ui.deltool_btn.clicked.disconnect()
  3424. except (TypeError, AttributeError):
  3425. pass
  3426. try:
  3427. self.ui.geo_tools_table.currentItemChanged.disconnect()
  3428. except (TypeError, AttributeError):
  3429. pass
  3430. try:
  3431. self.ui.geo_tools_table.itemChanged.disconnect()
  3432. except (TypeError, AttributeError):
  3433. pass
  3434. try:
  3435. self.ui.tool_offset_entry.returnPressed.disconnect()
  3436. except (TypeError, AttributeError):
  3437. pass
  3438. for row in range(self.ui.geo_tools_table.rowCount()):
  3439. try:
  3440. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  3441. except (TypeError, AttributeError):
  3442. pass
  3443. try:
  3444. self.ui.plot_cb.stateChanged.disconnect()
  3445. except (TypeError, AttributeError):
  3446. pass
  3447. def on_tool_add(self, dia=None):
  3448. self.ui_disconnect()
  3449. self.units = self.app.defaults['units'].upper()
  3450. if dia is not None:
  3451. tooldia = dia
  3452. else:
  3453. tooldia = float(self.ui.addtool_entry.get_value())
  3454. # construct a list of all 'tooluid' in the self.tools
  3455. # tool_uid_list = list()
  3456. # for tooluid_key in self.tools:
  3457. # tool_uid_list.append(int(tooluid_key))
  3458. tool_uid_list = [int(tooluid_key) for tooluid_key in self.tools]
  3459. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  3460. max_uid = max(tool_uid_list) if tool_uid_list else 0
  3461. self.tooluid = max_uid + 1
  3462. tooldia = float('%.*f' % (self.decimals, tooldia))
  3463. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  3464. # otherwise we add a tool with data copied from last tool
  3465. if self.tools:
  3466. last_data = self.tools[max_uid]['data']
  3467. last_offset = self.tools[max_uid]['offset']
  3468. last_offset_value = self.tools[max_uid]['offset_value']
  3469. last_type = self.tools[max_uid]['type']
  3470. last_tool_type = self.tools[max_uid]['tool_type']
  3471. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  3472. # if previous geometry was empty (it may happen for the first tool added)
  3473. # then copy the object.solid_geometry
  3474. if not last_solid_geometry:
  3475. last_solid_geometry = self.solid_geometry
  3476. self.tools.update({
  3477. self.tooluid: {
  3478. 'tooldia': tooldia,
  3479. 'offset': last_offset,
  3480. 'offset_value': last_offset_value,
  3481. 'type': last_type,
  3482. 'tool_type': last_tool_type,
  3483. 'data': deepcopy(last_data),
  3484. 'solid_geometry': deepcopy(last_solid_geometry)
  3485. }
  3486. })
  3487. else:
  3488. self.tools.update({
  3489. self.tooluid: {
  3490. 'tooldia': tooldia,
  3491. 'offset': 'Path',
  3492. 'offset_value': 0.0,
  3493. 'type': _('Rough'),
  3494. 'tool_type': 'C1',
  3495. 'data': deepcopy(self.default_data),
  3496. 'solid_geometry': self.solid_geometry
  3497. }
  3498. })
  3499. self.tools[self.tooluid]['data']['name'] = self.options['name']
  3500. self.ui.tool_offset_entry.hide()
  3501. self.ui.tool_offset_lbl.hide()
  3502. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3503. try:
  3504. self.ser_attrs.remove('tools')
  3505. except TypeError:
  3506. pass
  3507. self.ser_attrs.append('tools')
  3508. self.app.inform.emit('[success] %s' % _("Tool added in Tool Table."))
  3509. self.build_ui()
  3510. # if there is no tool left in the Tools Table, enable the parameters GUI
  3511. if self.ui.geo_tools_table.rowCount() != 0:
  3512. self.ui.geo_param_frame.setDisabled(False)
  3513. def on_tool_add_from_db_clicked(self):
  3514. """
  3515. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  3516. and display the Tools Database tab in the form needed for the Tool adding
  3517. :return: None
  3518. """
  3519. # if the Tools Database is already opened focus on it
  3520. for idx in range(self.app.ui.plot_tab_area.count()):
  3521. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  3522. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  3523. break
  3524. self.app.on_tools_database()
  3525. self.app.tools_db_tab.buttons_frame.hide()
  3526. self.app.tools_db_tab.add_tool_from_db.show()
  3527. self.app.tools_db_tab.cancel_tool_from_db.show()
  3528. def on_tool_from_db_inserted(self, tool):
  3529. """
  3530. Called from the Tools DB object through a App method when adding a tool from Tools Database
  3531. :param tool: a dict with the tool data
  3532. :return: None
  3533. """
  3534. self.ui_disconnect()
  3535. self.units = self.app.defaults['units'].upper()
  3536. tooldia = float(tool['tooldia'])
  3537. # construct a list of all 'tooluid' in the self.tools
  3538. tool_uid_list = []
  3539. for tooluid_key in self.tools:
  3540. tool_uid_item = int(tooluid_key)
  3541. tool_uid_list.append(tool_uid_item)
  3542. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  3543. if not tool_uid_list:
  3544. max_uid = 0
  3545. else:
  3546. max_uid = max(tool_uid_list)
  3547. self.tooluid = max_uid + 1
  3548. tooldia = float('%.*f' % (self.decimals, tooldia))
  3549. self.tools.update({
  3550. self.tooluid: {
  3551. 'tooldia': tooldia,
  3552. 'offset': tool['offset'],
  3553. 'offset_value': float(tool['offset_value']),
  3554. 'type': tool['type'],
  3555. 'tool_type': tool['tool_type'],
  3556. 'data': deepcopy(tool['data']),
  3557. 'solid_geometry': self.solid_geometry
  3558. }
  3559. })
  3560. self.tools[self.tooluid]['data']['name'] = self.options['name']
  3561. self.ui.tool_offset_entry.hide()
  3562. self.ui.tool_offset_lbl.hide()
  3563. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3564. try:
  3565. self.ser_attrs.remove('tools')
  3566. except TypeError:
  3567. pass
  3568. self.ser_attrs.append('tools')
  3569. self.build_ui()
  3570. # if there is no tool left in the Tools Table, enable the parameters GUI
  3571. if self.ui.geo_tools_table.rowCount() != 0:
  3572. self.ui.geo_param_frame.setDisabled(False)
  3573. def on_tool_copy(self, all=None):
  3574. self.ui_disconnect()
  3575. # find the tool_uid maximum value in the self.tools
  3576. uid_list = []
  3577. for key in self.tools:
  3578. uid_list.append(int(key))
  3579. try:
  3580. max_uid = max(uid_list, key=int)
  3581. except ValueError:
  3582. max_uid = 0
  3583. if all is None:
  3584. if self.ui.geo_tools_table.selectedItems():
  3585. for current_row in self.ui.geo_tools_table.selectedItems():
  3586. # sometime the header get selected and it has row number -1
  3587. # we don't want to do anything with the header :)
  3588. if current_row.row() < 0:
  3589. continue
  3590. try:
  3591. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3592. self.set_tool_offset_visibility(current_row.row())
  3593. max_uid += 1
  3594. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  3595. except AttributeError:
  3596. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3597. _("Failed. Select a tool to copy."))
  3598. self.build_ui()
  3599. return
  3600. except Exception as e:
  3601. log.debug("on_tool_copy() --> " + str(e))
  3602. # deselect the table
  3603. # self.ui.geo_tools_table.clearSelection()
  3604. else:
  3605. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3606. _("Failed. Select a tool to copy."))
  3607. self.build_ui()
  3608. return
  3609. else:
  3610. # we copy all tools in geo_tools_table
  3611. try:
  3612. temp_tools = deepcopy(self.tools)
  3613. max_uid += 1
  3614. for tooluid in temp_tools:
  3615. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  3616. temp_tools.clear()
  3617. except Exception as e:
  3618. log.debug("on_tool_copy() --> " + str(e))
  3619. # if there are no more tools in geo tools table then hide the tool offset
  3620. if not self.tools:
  3621. self.ui.tool_offset_entry.hide()
  3622. self.ui.tool_offset_lbl.hide()
  3623. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3624. try:
  3625. self.ser_attrs.remove('tools')
  3626. except ValueError:
  3627. pass
  3628. self.ser_attrs.append('tools')
  3629. self.build_ui()
  3630. self.app.inform.emit('[success] %s' % _("Tool was copied in Tool Table."))
  3631. def on_tool_edit(self, current_item):
  3632. self.ui_disconnect()
  3633. current_row = current_item.row()
  3634. try:
  3635. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  3636. except ValueError:
  3637. # try to convert comma to decimal point. if it's still not working error message and return
  3638. try:
  3639. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  3640. except ValueError:
  3641. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  3642. return
  3643. tool_dia = float('%.*f' % (self.decimals, d))
  3644. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  3645. self.tools[tooluid]['tooldia'] = tool_dia
  3646. try:
  3647. self.ser_attrs.remove('tools')
  3648. self.ser_attrs.append('tools')
  3649. except (TypeError, ValueError):
  3650. pass
  3651. self.app.inform.emit('[success] %s' % _("Tool was edited in Tool Table."))
  3652. self.build_ui()
  3653. def on_tool_delete(self, all=None):
  3654. self.ui_disconnect()
  3655. if all is None:
  3656. if self.ui.geo_tools_table.selectedItems():
  3657. for current_row in self.ui.geo_tools_table.selectedItems():
  3658. # sometime the header get selected and it has row number -1
  3659. # we don't want to do anything with the header :)
  3660. if current_row.row() < 0:
  3661. continue
  3662. try:
  3663. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  3664. self.set_tool_offset_visibility(current_row.row())
  3665. temp_tools = deepcopy(self.tools)
  3666. for tooluid_key in self.tools:
  3667. if int(tooluid_key) == tooluid_del:
  3668. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  3669. # as a property of the object otherwise there will be nothing to hold it
  3670. if len(self.tools) == 1:
  3671. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3672. temp_tools.pop(tooluid_del, None)
  3673. self.tools = deepcopy(temp_tools)
  3674. temp_tools.clear()
  3675. except AttributeError:
  3676. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3677. _("Failed. Select a tool to delete."))
  3678. self.build_ui()
  3679. return
  3680. except Exception as e:
  3681. log.debug("on_tool_delete() --> " + str(e))
  3682. # deselect the table
  3683. # self.ui.geo_tools_table.clearSelection()
  3684. else:
  3685. self.app.inform.emit('[WARNING_NOTCL] %s' %
  3686. _("Failed. Select a tool to delete."))
  3687. self.build_ui()
  3688. return
  3689. else:
  3690. # we delete all tools in geo_tools_table
  3691. self.tools.clear()
  3692. self.app.plot_all()
  3693. # if there are no more tools in geo tools table then hide the tool offset
  3694. if not self.tools:
  3695. self.ui.tool_offset_entry.hide()
  3696. self.ui.tool_offset_lbl.hide()
  3697. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  3698. try:
  3699. self.ser_attrs.remove('tools')
  3700. except TypeError:
  3701. pass
  3702. self.ser_attrs.append('tools')
  3703. self.build_ui()
  3704. self.app.inform.emit('[success] %s' %
  3705. _("Tool was deleted in Tool Table."))
  3706. obj_active = self.app.collection.get_active()
  3707. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  3708. # we make it back SingleGeo
  3709. if self.ui.geo_tools_table.rowCount() <= 0:
  3710. obj_active.multigeo = False
  3711. obj_active.options['xmin'] = 0
  3712. obj_active.options['ymin'] = 0
  3713. obj_active.options['xmax'] = 0
  3714. obj_active.options['ymax'] = 0
  3715. if obj_active.multigeo is True:
  3716. try:
  3717. xmin, ymin, xmax, ymax = obj_active.bounds()
  3718. obj_active.options['xmin'] = xmin
  3719. obj_active.options['ymin'] = ymin
  3720. obj_active.options['xmax'] = xmax
  3721. obj_active.options['ymax'] = ymax
  3722. except Exception as e:
  3723. obj_active.options['xmin'] = 0
  3724. obj_active.options['ymin'] = 0
  3725. obj_active.options['xmax'] = 0
  3726. obj_active.options['ymax'] = 0
  3727. # if there is no tool left in the Tools Table, disable the parameters GUI
  3728. if self.ui.geo_tools_table.rowCount() == 0:
  3729. self.ui.geo_param_frame.setDisabled(True)
  3730. def on_row_selection_change(self):
  3731. self.update_ui()
  3732. def update_ui(self, row=None):
  3733. self.ui_disconnect()
  3734. if row is None:
  3735. try:
  3736. current_row = self.ui.geo_tools_table.currentRow()
  3737. except Exception:
  3738. current_row = 0
  3739. else:
  3740. current_row = row
  3741. if current_row < 0:
  3742. current_row = 0
  3743. self.set_tool_offset_visibility(current_row)
  3744. # populate the form with the data from the tool associated with the row parameter
  3745. try:
  3746. item = self.ui.geo_tools_table.item(current_row, 5)
  3747. if type(item) is not None:
  3748. tooluid = int(item.text())
  3749. else:
  3750. return
  3751. except Exception as e:
  3752. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  3753. return
  3754. # update the QLabel that shows for which Tool we have the parameters in the UI form
  3755. self.ui.tool_data_label.setText(
  3756. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  3757. )
  3758. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  3759. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  3760. try:
  3761. item = self.ui.geo_tools_table.cellWidget(current_row, 4)
  3762. if item is not None:
  3763. tool_type_txt = item.currentText()
  3764. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  3765. else:
  3766. return
  3767. except Exception as e:
  3768. log.debug("Tool missing in ui_update_v_shape(). Add a tool in Geo Tool Table. %s" % str(e))
  3769. return
  3770. try:
  3771. # set the form with data from the newly selected tool
  3772. for tooluid_key, tooluid_value in list(self.tools.items()):
  3773. if int(tooluid_key) == tooluid:
  3774. for key, value in tooluid_value.items():
  3775. if key == 'data':
  3776. form_value_storage = tooluid_value[key]
  3777. self.update_form(form_value_storage)
  3778. if key == 'offset_value':
  3779. # update the offset value in the entry even if the entry is hidden
  3780. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  3781. if key == 'tool_type' and value == 'V':
  3782. self.update_cutz()
  3783. except Exception as e:
  3784. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  3785. self.ui_connect()
  3786. def ui_update_v_shape(self, tool_type_txt):
  3787. if tool_type_txt == 'V':
  3788. self.ui.tipdialabel.show()
  3789. self.ui.tipdia_entry.show()
  3790. self.ui.tipanglelabel.show()
  3791. self.ui.tipangle_entry.show()
  3792. self.ui.cutz_entry.setDisabled(True)
  3793. self.update_cutz()
  3794. else:
  3795. self.ui.tipdialabel.hide()
  3796. self.ui.tipdia_entry.hide()
  3797. self.ui.tipanglelabel.hide()
  3798. self.ui.tipangle_entry.hide()
  3799. self.ui.cutz_entry.setDisabled(False)
  3800. def update_cutz(self):
  3801. vdia = float(self.ui.tipdia_entry.get_value())
  3802. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  3803. row = self.ui.geo_tools_table.currentRow()
  3804. tool_uid_item = self.ui.geo_tools_table.item(row, 5)
  3805. if tool_uid_item is None:
  3806. return
  3807. tool_uid = int(tool_uid_item.text())
  3808. tool_dia_item = self.ui.geo_tools_table.item(row, 1)
  3809. if tool_dia_item is None:
  3810. return
  3811. tooldia = float(tool_dia_item.text())
  3812. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  3813. new_cutz = float('%.*f' % (self.decimals, new_cutz)) * -1.0 # this value has to be negative
  3814. self.ui.cutz_entry.set_value(new_cutz)
  3815. # store the new CutZ value into storage (self.tools)
  3816. for tooluid_key, tooluid_value in self.tools.items():
  3817. if int(tooluid_key) == tool_uid:
  3818. tooluid_value['data']['cutz'] = new_cutz
  3819. def on_tooltable_cellwidget_change(self):
  3820. cw = self.sender()
  3821. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3822. cw_row = cw_index.row()
  3823. cw_col = cw_index.column()
  3824. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  3825. # store the text of the cellWidget that changed it's index in the self.tools
  3826. for tooluid_key, tooluid_value in self.tools.items():
  3827. if int(tooluid_key) == current_uid:
  3828. cb_txt = cw.currentText()
  3829. if cw_col == 2:
  3830. tooluid_value['offset'] = cb_txt
  3831. if cb_txt == 'Custom':
  3832. self.ui.tool_offset_entry.show()
  3833. self.ui.tool_offset_lbl.show()
  3834. else:
  3835. self.ui.tool_offset_entry.hide()
  3836. self.ui.tool_offset_lbl.hide()
  3837. # reset the offset_value in storage self.tools
  3838. tooluid_value['offset_value'] = 0.0
  3839. elif cw_col == 3:
  3840. # force toolpath type as 'Iso' if the tool type is V-Shape
  3841. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  3842. tooluid_value['type'] = _('Iso')
  3843. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3844. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3845. else:
  3846. tooluid_value['type'] = cb_txt
  3847. elif cw_col == 4:
  3848. tooluid_value['tool_type'] = cb_txt
  3849. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  3850. if cb_txt == 'V':
  3851. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  3852. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  3853. else:
  3854. self.ui.cutz_entry.set_value(self.old_cutz)
  3855. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  3856. def update_form(self, dict_storage):
  3857. for form_key in self.form_fields:
  3858. for storage_key in dict_storage:
  3859. if form_key == storage_key:
  3860. try:
  3861. self.form_fields[form_key].set_value(dict_storage[form_key])
  3862. except Exception as e:
  3863. log.debug(str(e))
  3864. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  3865. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  3866. self.ui.ois_dwell_geo.on_cb_change()
  3867. self.ui.ois_mpass_geo.on_cb_change()
  3868. self.ui.ois_tcz_geo.on_cb_change()
  3869. def on_apply_param_to_all_clicked(self):
  3870. if self.ui.geo_tools_table.rowCount() == 0:
  3871. # there is no tool in tool table so we can't save the GUI elements values to storage
  3872. log.debug("FlatCAMGeometry.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  3873. return
  3874. self.ui_disconnect()
  3875. row = self.ui.geo_tools_table.currentRow()
  3876. if row < 0:
  3877. row = 0
  3878. # store all the data associated with the row parameter to the self.tools storage
  3879. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  3880. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  3881. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  3882. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  3883. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  3884. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  3885. temp_tools = {}
  3886. temp_dia = {}
  3887. temp_data = {}
  3888. for tooluid_key, tooluid_value in self.tools.items():
  3889. for key, value in tooluid_value.items():
  3890. if key == 'tooldia':
  3891. temp_dia[key] = tooldia_item
  3892. # update the 'offset', 'type' and 'tool_type' sections
  3893. if key == 'offset':
  3894. temp_dia[key] = offset_item
  3895. if key == 'type':
  3896. temp_dia[key] = type_item
  3897. if key == 'tool_type':
  3898. temp_dia[key] = tool_type_item
  3899. if key == 'offset_value':
  3900. temp_dia[key] = offset_value_item
  3901. if key == 'data':
  3902. # update the 'data' section
  3903. for data_key in tooluid_value[key].keys():
  3904. for form_key, form_value in self.form_fields.items():
  3905. if form_key == data_key:
  3906. temp_data[data_key] = form_value.get_value()
  3907. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  3908. # updated from self.app.defaults
  3909. if data_key not in self.form_fields:
  3910. temp_data[data_key] = value[data_key]
  3911. temp_dia[key] = deepcopy(temp_data)
  3912. temp_data.clear()
  3913. if key == 'solid_geometry':
  3914. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3915. temp_tools[tooluid_key] = deepcopy(temp_dia)
  3916. self.tools.clear()
  3917. self.tools = deepcopy(temp_tools)
  3918. temp_tools.clear()
  3919. self.ui_connect()
  3920. def gui_form_to_storage(self):
  3921. if self.ui.geo_tools_table.rowCount() == 0:
  3922. # there is no tool in tool table so we can't save the GUI elements values to storage
  3923. log.debug("FlatCAMGeometry.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  3924. return
  3925. self.ui_disconnect()
  3926. widget_changed = self.sender()
  3927. try:
  3928. widget_idx = self.ui.grid3.indexOf(widget_changed)
  3929. except Exception as e:
  3930. return
  3931. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  3932. if widget_idx == 1 or widget_idx == 3:
  3933. self.update_cutz()
  3934. # the original connect() function of the OptionalInputSelection is no longer working because of the
  3935. # ui_diconnect() so I use this 'hack'
  3936. if isinstance(widget_changed, FCCheckBox):
  3937. if widget_changed.text() == 'Multi-Depth:':
  3938. self.ui.ois_mpass_geo.on_cb_change()
  3939. if widget_changed.text() == 'Tool change':
  3940. self.ui.ois_tcz_geo.on_cb_change()
  3941. if widget_changed.text() == 'Dwell:':
  3942. self.ui.ois_dwell_geo.on_cb_change()
  3943. row = self.ui.geo_tools_table.currentRow()
  3944. if row < 0:
  3945. row = 0
  3946. # store all the data associated with the row parameter to the self.tools storage
  3947. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  3948. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  3949. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  3950. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  3951. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3952. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  3953. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  3954. temp_tools = {}
  3955. temp_dia = {}
  3956. temp_data = {}
  3957. for tooluid_key, tooluid_value in self.tools.items():
  3958. if int(tooluid_key) == tooluid_item:
  3959. for key, value in tooluid_value.items():
  3960. if key == 'tooldia':
  3961. temp_dia[key] = tooldia_item
  3962. # update the 'offset', 'type' and 'tool_type' sections
  3963. if key == 'offset':
  3964. temp_dia[key] = offset_item
  3965. if key == 'type':
  3966. temp_dia[key] = type_item
  3967. if key == 'tool_type':
  3968. temp_dia[key] = tool_type_item
  3969. if key == 'offset_value':
  3970. temp_dia[key] = offset_value_item
  3971. if key == 'data':
  3972. # update the 'data' section
  3973. for data_key in tooluid_value[key].keys():
  3974. for form_key, form_value in self.form_fields.items():
  3975. if form_key == data_key:
  3976. temp_data[data_key] = form_value.get_value()
  3977. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  3978. # updated from self.app.defaults
  3979. if data_key not in self.form_fields:
  3980. temp_data[data_key] = value[data_key]
  3981. temp_dia[key] = deepcopy(temp_data)
  3982. temp_data.clear()
  3983. if key == 'solid_geometry':
  3984. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  3985. temp_tools[tooluid_key] = deepcopy(temp_dia)
  3986. else:
  3987. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  3988. self.tools.clear()
  3989. self.tools = deepcopy(temp_tools)
  3990. temp_tools.clear()
  3991. self.ui_connect()
  3992. def select_tools_table_row(self, row, clearsel=None):
  3993. if clearsel:
  3994. self.ui.geo_tools_table.clearSelection()
  3995. if self.ui.geo_tools_table.rowCount() > 0:
  3996. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  3997. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  3998. def export_dxf(self):
  3999. units = self.app.defaults['units'].upper()
  4000. dwg = None
  4001. try:
  4002. dwg = ezdxf.new('R2010')
  4003. msp = dwg.modelspace()
  4004. def g2dxf(dxf_space, geo):
  4005. if isinstance(geo, MultiPolygon):
  4006. for poly in geo:
  4007. ext_points = list(poly.exterior.coords)
  4008. dxf_space.add_lwpolyline(ext_points)
  4009. for interior in poly.interiors:
  4010. dxf_space.add_lwpolyline(list(interior.coords))
  4011. if isinstance(geo, Polygon):
  4012. ext_points = list(geo.exterior.coords)
  4013. dxf_space.add_lwpolyline(ext_points)
  4014. for interior in geo.interiors:
  4015. dxf_space.add_lwpolyline(list(interior.coords))
  4016. if isinstance(geo, MultiLineString):
  4017. for line in geo:
  4018. dxf_space.add_lwpolyline(list(line.coords))
  4019. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  4020. dxf_space.add_lwpolyline(list(geo.coords))
  4021. multigeo_solid_geometry = []
  4022. if self.multigeo:
  4023. for tool in self.tools:
  4024. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  4025. else:
  4026. multigeo_solid_geometry = self.solid_geometry
  4027. for geo in multigeo_solid_geometry:
  4028. if type(geo) == list:
  4029. for g in geo:
  4030. g2dxf(msp, g)
  4031. else:
  4032. g2dxf(msp, geo)
  4033. # points = FlatCAMGeometry.get_pts(geo)
  4034. # msp.add_lwpolyline(points)
  4035. except Exception as e:
  4036. log.debug(str(e))
  4037. return dwg
  4038. def get_selected_tools_table_items(self):
  4039. """
  4040. Returns a list of lists, each list in the list is made out of row elements
  4041. :return: List of table_tools items.
  4042. :rtype: list
  4043. """
  4044. table_tools_items = []
  4045. if self.multigeo:
  4046. for x in self.ui.geo_tools_table.selectedItems():
  4047. elem = list()
  4048. txt = ''
  4049. for column in range(0, self.ui.geo_tools_table.columnCount()):
  4050. try:
  4051. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  4052. except AttributeError:
  4053. try:
  4054. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  4055. except AttributeError:
  4056. pass
  4057. elem.append(txt)
  4058. table_tools_items.append(deepcopy(elem))
  4059. # table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  4060. # for column in range(0, self.ui.geo_tools_table.columnCount())])
  4061. else:
  4062. for x in self.ui.geo_tools_table.selectedItems():
  4063. r = []
  4064. txt = ''
  4065. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  4066. # so we don't read them
  4067. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  4068. # the columns have items that have text but also have items that are widgets
  4069. # for which the text they hold has to be read differently
  4070. try:
  4071. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  4072. except AttributeError:
  4073. try:
  4074. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  4075. except AttributeError:
  4076. pass
  4077. r.append(txt)
  4078. table_tools_items.append(r)
  4079. for item in table_tools_items:
  4080. item[0] = str(item[0])
  4081. return table_tools_items
  4082. def on_pp_changed(self):
  4083. current_pp = self.ui.pp_geometry_name_cb.get_value()
  4084. if current_pp == 'hpgl':
  4085. self.old_pp_state = self.ui.mpass_cb.get_value()
  4086. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  4087. self.ui.mpass_cb.set_value(False)
  4088. self.ui.mpass_cb.setDisabled(True)
  4089. self.ui.toolchangeg_cb.set_value(True)
  4090. self.ui.toolchangeg_cb.setDisabled(True)
  4091. else:
  4092. self.ui.mpass_cb.set_value(self.old_pp_state)
  4093. self.ui.mpass_cb.setDisabled(False)
  4094. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  4095. self.ui.toolchangeg_cb.setDisabled(False)
  4096. if "toolchange_probe" in current_pp.lower():
  4097. self.ui.pdepth_entry.setVisible(True)
  4098. self.ui.pdepth_label.show()
  4099. self.ui.feedrate_probe_entry.setVisible(True)
  4100. self.ui.feedrate_probe_label.show()
  4101. else:
  4102. self.ui.pdepth_entry.setVisible(False)
  4103. self.ui.pdepth_label.hide()
  4104. self.ui.feedrate_probe_entry.setVisible(False)
  4105. self.ui.feedrate_probe_label.hide()
  4106. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  4107. self.ui.fr_rapidlabel.show()
  4108. self.ui.cncfeedrate_rapid_entry.show()
  4109. else:
  4110. self.ui.fr_rapidlabel.hide()
  4111. self.ui.cncfeedrate_rapid_entry.hide()
  4112. def on_generatecnc_button_click(self, *args):
  4113. log.debug("Generating CNCJob from Geometry ...")
  4114. self.app.report_usage("geometry_on_generatecnc_button")
  4115. # this reads the values in the UI form to the self.options dictionary
  4116. self.read_form()
  4117. self.sel_tools = {}
  4118. try:
  4119. if self.special_group:
  4120. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  4121. (_("This Geometry can't be processed because it is"),
  4122. str(self.special_group),
  4123. _("geometry")
  4124. )
  4125. )
  4126. return
  4127. except AttributeError:
  4128. pass
  4129. # test to see if we have tools available in the tool table
  4130. if self.ui.geo_tools_table.selectedItems():
  4131. for x in self.ui.geo_tools_table.selectedItems():
  4132. # try:
  4133. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  4134. # except ValueError:
  4135. # # try to convert comma to decimal point. if it's still not working error message and return
  4136. # try:
  4137. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  4138. # except ValueError:
  4139. # self.app.inform.emit('[ERROR_NOTCL] %s' %
  4140. # _("Wrong value format entered, use a number."))
  4141. # return
  4142. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  4143. for tooluid_key, tooluid_value in self.tools.items():
  4144. if int(tooluid_key) == tooluid:
  4145. self.sel_tools.update({
  4146. tooluid: deepcopy(tooluid_value)
  4147. })
  4148. self.mtool_gen_cncjob()
  4149. self.ui.geo_tools_table.clearSelection()
  4150. elif self.ui.geo_tools_table.rowCount() == 1:
  4151. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  4152. for tooluid_key, tooluid_value in self.tools.items():
  4153. if int(tooluid_key) == tooluid:
  4154. self.sel_tools.update({
  4155. tooluid: deepcopy(tooluid_value)
  4156. })
  4157. self.mtool_gen_cncjob()
  4158. self.ui.geo_tools_table.clearSelection()
  4159. else:
  4160. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4161. _("Failed. No tool selected in the tool table ..."))
  4162. def mtool_gen_cncjob(self, outname=None, tools_dict=None, tools_in_use=None, segx=None, segy=None,
  4163. plot=True, use_thread=True):
  4164. """
  4165. Creates a multi-tool CNCJob out of this Geometry object.
  4166. The actual work is done by the target FlatCAMCNCjob object's
  4167. `generate_from_geometry_2()` method.
  4168. :param tools_dict: a dictionary that holds the whole data needed to create the Gcode
  4169. (including the solid_geometry)
  4170. :param tools_in_use: the tools that are used, needed by some preprocessors
  4171. :type list of lists, each list in the list is made out of row elements of tools table from GUI
  4172. :param segx: number of segments on the X axis, for auto-levelling
  4173. :param segy: number of segments on the Y axis, for auto-levelling
  4174. :param plot: if True the generated object will be plotted; if False will not be plotted
  4175. :param use_thread: if True use threading
  4176. :return: None
  4177. """
  4178. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  4179. outname = "%s_%s" % (self.options["name"], 'cnc') if outname is None else outname
  4180. tools_dict = self.sel_tools if tools_dict is None else tools_dict
  4181. tools_in_use = tools_in_use if tools_in_use is not None else self.get_selected_tools_table_items()
  4182. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4183. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4184. try:
  4185. xmin = self.options['xmin']
  4186. ymin = self.options['ymin']
  4187. xmax = self.options['xmax']
  4188. ymax = self.options['ymax']
  4189. except Exception as e:
  4190. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  4191. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  4192. msg += '%s %s' % ('FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() -->', str(e))
  4193. msg += traceback.format_exc()
  4194. self.app.inform.emit(msg)
  4195. return
  4196. # Object initialization function for app.new_object()
  4197. # RUNNING ON SEPARATE THREAD!
  4198. def job_init_single_geometry(job_obj, app_obj):
  4199. log.debug("Creating a CNCJob out of a single-geometry")
  4200. assert isinstance(job_obj, FlatCAMCNCjob), \
  4201. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4202. job_obj.options['xmin'] = xmin
  4203. job_obj.options['ymin'] = ymin
  4204. job_obj.options['xmax'] = xmax
  4205. job_obj.options['ymax'] = ymax
  4206. # count the tools
  4207. tool_cnt = 0
  4208. dia_cnc_dict = dict()
  4209. # this turn on the FlatCAMCNCJob plot for multiple tools
  4210. job_obj.multitool = True
  4211. job_obj.multigeo = False
  4212. job_obj.cnc_tools.clear()
  4213. job_obj.options['Tools_in_use'] = tools_in_use
  4214. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  4215. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  4216. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  4217. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  4218. for tooluid_key in list(tools_dict.keys()):
  4219. tool_cnt += 1
  4220. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  4221. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  4222. dia_cnc_dict.update({
  4223. 'tooldia': tooldia_val
  4224. })
  4225. if dia_cnc_dict['offset'] == 'in':
  4226. tool_offset = -dia_cnc_dict['tooldia'] / 2
  4227. elif dia_cnc_dict['offset'].lower() == 'out':
  4228. tool_offset = dia_cnc_dict['tooldia'] / 2
  4229. elif dia_cnc_dict['offset'].lower() == 'custom':
  4230. try:
  4231. offset_value = float(self.ui.tool_offset_entry.get_value())
  4232. except ValueError:
  4233. # try to convert comma to decimal point. if it's still not working error message and return
  4234. try:
  4235. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  4236. except ValueError:
  4237. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4238. _("Wrong value format entered, use a number."))
  4239. return
  4240. if offset_value:
  4241. tool_offset = float(offset_value)
  4242. else:
  4243. self.app.inform.emit('[WARNING] %s' % _("Tool Offset is selected in Tool Table but "
  4244. "no value is provided.\n"
  4245. "Add a Tool Offset or change the Offset Type."))
  4246. return
  4247. else:
  4248. tool_offset = 0.0
  4249. dia_cnc_dict.update({
  4250. 'offset_value': tool_offset
  4251. })
  4252. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  4253. z_move = tools_dict[tooluid_key]['data']["travelz"]
  4254. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  4255. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  4256. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  4257. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  4258. extracut = tools_dict[tooluid_key]['data']["extracut"]
  4259. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  4260. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  4261. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  4262. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  4263. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  4264. startz = tools_dict[tooluid_key]['data']["startz"]
  4265. endz = tools_dict[tooluid_key]['data']["endz"]
  4266. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  4267. dwell = tools_dict[tooluid_key]['data']["dwell"]
  4268. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  4269. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  4270. spindledir = self.app.defaults['geometry_spindledir']
  4271. tool_solid_geometry = self.solid_geometry
  4272. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4273. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4274. # Propagate options
  4275. job_obj.options["tooldia"] = tooldia_val
  4276. job_obj.options['type'] = 'Geometry'
  4277. job_obj.options['tool_dia'] = tooldia_val
  4278. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4279. # to a value of 0.0005 which is 20 times less than 0.01
  4280. tol = float(self.app.defaults['global_tolerance']) / 20
  4281. res = job_obj.generate_from_geometry_2(
  4282. self, tooldia=tooldia_val, offset=tool_offset, tolerance=tol,
  4283. z_cut=z_cut, z_move=z_move,
  4284. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4285. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  4286. multidepth=multidepth, depthpercut=depthpercut,
  4287. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4288. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4289. pp_geometry_name=pp_geometry_name,
  4290. tool_no=tool_cnt)
  4291. if res == 'fail':
  4292. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  4293. return 'fail'
  4294. else:
  4295. dia_cnc_dict['gcode'] = res
  4296. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  4297. # object is the source of gcode
  4298. job_obj.toolchange_xy_type = "geometry"
  4299. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  4300. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  4301. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  4302. # TODO this serve for bounding box creation only; should be optimized
  4303. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  4304. # for bounding box values
  4305. # dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  4306. try:
  4307. dia_cnc_dict['solid_geometry'] = tool_solid_geometry
  4308. self.app.inform.emit('[success] %s...' % _("Finished G-Code processing"))
  4309. except Exception as e:
  4310. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(e)))
  4311. job_obj.cnc_tools.update({
  4312. tooluid_key: deepcopy(dia_cnc_dict)
  4313. })
  4314. dia_cnc_dict.clear()
  4315. # Object initialization function for app.new_object()
  4316. # RUNNING ON SEPARATE THREAD!
  4317. def job_init_multi_geometry(job_obj, app_obj):
  4318. log.debug("Creating a CNCJob out of a multi-geometry")
  4319. assert isinstance(job_obj, FlatCAMCNCjob), \
  4320. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4321. current_uid = int(1)
  4322. job_obj.options['xmin'] = xmin
  4323. job_obj.options['ymin'] = ymin
  4324. job_obj.options['xmax'] = xmax
  4325. job_obj.options['ymax'] = ymax
  4326. # count the tools
  4327. tool_cnt = 0
  4328. dia_cnc_dict = dict()
  4329. # this turn on the FlatCAMCNCJob plot for multiple tools
  4330. job_obj.multitool = True
  4331. job_obj.multigeo = True
  4332. job_obj.cnc_tools.clear()
  4333. job_obj.options['Tools_in_use'] = tools_in_use
  4334. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  4335. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  4336. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  4337. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  4338. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  4339. if not self.solid_geometry:
  4340. a = 0
  4341. for tooluid_key in self.tools:
  4342. if self.tools[tooluid_key]['solid_geometry'] is None:
  4343. a += 1
  4344. if a == len(self.tools):
  4345. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('Cancelled. Empty file, it has no geometry'))
  4346. return 'fail'
  4347. for tooluid_key in list(tools_dict.keys()):
  4348. tool_cnt += 1
  4349. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  4350. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  4351. dia_cnc_dict.update({
  4352. 'tooldia': tooldia_val
  4353. })
  4354. # find the tool_dia associated with the tooluid_key
  4355. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  4356. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  4357. for k, v in self.tools.items():
  4358. if float('%.*f' % (self.decimals, float(v['tooldia']))) == tooldia_val:
  4359. current_uid = int(k)
  4360. break
  4361. if dia_cnc_dict['offset'] == 'in':
  4362. tool_offset = -tooldia_val / 2
  4363. elif dia_cnc_dict['offset'].lower() == 'out':
  4364. tool_offset = tooldia_val / 2
  4365. elif dia_cnc_dict['offset'].lower() == 'custom':
  4366. offset_value = float(self.ui.tool_offset_entry.get_value())
  4367. if offset_value:
  4368. tool_offset = float(offset_value)
  4369. else:
  4370. self.app.inform.emit('[WARNING] %s' %
  4371. _("Tool Offset is selected in Tool Table but "
  4372. "no value is provided.\n"
  4373. "Add a Tool Offset or change the Offset Type."))
  4374. return
  4375. else:
  4376. tool_offset = 0.0
  4377. dia_cnc_dict.update({
  4378. 'offset_value': tool_offset
  4379. })
  4380. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  4381. z_move = tools_dict[tooluid_key]['data']["travelz"]
  4382. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  4383. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  4384. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  4385. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  4386. extracut = tools_dict[tooluid_key]['data']["extracut"]
  4387. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  4388. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  4389. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  4390. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  4391. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  4392. startz = tools_dict[tooluid_key]['data']["startz"]
  4393. endz = tools_dict[tooluid_key]['data']["endz"]
  4394. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  4395. dwell = tools_dict[tooluid_key]['data']["dwell"]
  4396. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  4397. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  4398. spindledir = self.app.defaults['geometry_spindledir']
  4399. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  4400. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4401. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4402. # Propagate options
  4403. job_obj.options["tooldia"] = tooldia_val
  4404. job_obj.options['type'] = 'Geometry'
  4405. job_obj.options['tool_dia'] = tooldia_val
  4406. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4407. # to a value of 0.0005 which is 20 times less than 0.01
  4408. tol = float(self.app.defaults['global_tolerance']) / 20
  4409. res = job_obj.generate_from_multitool_geometry(
  4410. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  4411. tolerance=tol, z_cut=z_cut, z_move=z_move,
  4412. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4413. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  4414. multidepth=multidepth, depthpercut=depthpercut,
  4415. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4416. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4417. pp_geometry_name=pp_geometry_name,
  4418. tool_no=tool_cnt)
  4419. if res == 'fail':
  4420. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  4421. return 'fail'
  4422. else:
  4423. dia_cnc_dict['gcode'] = res
  4424. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  4425. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  4426. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  4427. # TODO this serve for bounding box creation only; should be optimized
  4428. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  4429. # for bounding box values
  4430. # geo_for_bound_values = cascaded_union([
  4431. # geo['geom'] for geo in dia_cnc_dict['gcode_parsed'] if geo['geom'].is_valid is True
  4432. # ])
  4433. try:
  4434. dia_cnc_dict['solid_geometry'] = deepcopy(tool_solid_geometry)
  4435. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  4436. except Exception as e:
  4437. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(e)))
  4438. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  4439. # object is the source of gcode
  4440. job_obj.toolchange_xy_type = "geometry"
  4441. job_obj.cnc_tools.update({
  4442. tooluid_key: deepcopy(dia_cnc_dict)
  4443. })
  4444. dia_cnc_dict.clear()
  4445. if use_thread:
  4446. # To be run in separate thread
  4447. def job_thread(app_obj):
  4448. if self.multigeo is False:
  4449. with self.app.proc_container.new(_("Generating CNC Code")):
  4450. if app_obj.new_object("cncjob", outname, job_init_single_geometry, plot=plot) != 'fail':
  4451. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  4452. else:
  4453. with self.app.proc_container.new(_("Generating CNC Code")):
  4454. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  4455. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  4456. # Create a promise with the name
  4457. self.app.collection.promise(outname)
  4458. # Send to worker
  4459. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4460. else:
  4461. if self.solid_geometry:
  4462. self.app.new_object("cncjob", outname, job_init_single_geometry, plot=plot)
  4463. else:
  4464. self.app.new_object("cncjob", outname, job_init_multi_geometry, plot=plot)
  4465. def generatecncjob(
  4466. self, outname=None,
  4467. dia=None, offset=None,
  4468. z_cut=None, z_move=None,
  4469. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  4470. spindlespeed=None, dwell=None, dwelltime=None,
  4471. multidepth=None, depthperpass=None,
  4472. toolchange=None, toolchangez=None, toolchangexy=None,
  4473. extracut=None, extracut_length=None, startz=None, endz=None,
  4474. pp=None,
  4475. segx=None, segy=None,
  4476. use_thread=True,
  4477. plot=True):
  4478. """
  4479. Only used for TCL Command.
  4480. Creates a CNCJob out of this Geometry object. The actual
  4481. work is done by the target camlib.CNCjob
  4482. `generate_from_geometry_2()` method.
  4483. :param z_cut: Cut depth (negative)
  4484. :param z_move: Hight of the tool when travelling (not cutting)
  4485. :param feedrate: Feed rate while cutting on X - Y plane
  4486. :param feedrate_z: Feed rate while cutting on Z plane
  4487. :param feedrate_rapid: Feed rate while moving with rapids
  4488. :param dia: Tool diameter
  4489. :param outname: Name of the new object
  4490. :param spindlespeed: Spindle speed (RPM)
  4491. :param pp Name of the preprocessor
  4492. :return: None
  4493. """
  4494. tooldia = dia if dia else float(self.options["cnctooldia"])
  4495. outname = outname if outname is not None else self.options["name"]
  4496. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  4497. z_move = z_move if z_move is not None else float(self.options["travelz"])
  4498. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  4499. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  4500. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  4501. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  4502. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  4503. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  4504. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  4505. extracut = extracut if extracut is not None else float(self.options["extracut"])
  4506. extracut_length = extracut_length if extracut_length is not None else float(self.options["extracut_length"])
  4507. startz = startz if startz is not None else self.options["startz"]
  4508. endz = endz if endz is not None else float(self.options["endz"])
  4509. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  4510. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  4511. toolchange = toolchange if toolchange else self.options["toolchange"]
  4512. offset = offset if offset else 0.0
  4513. # int or None.
  4514. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  4515. dwell = dwell if dwell else self.options["dwell"]
  4516. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  4517. ppname_g = pp if pp else self.options["ppname_g"]
  4518. # Object initialization function for app.new_object()
  4519. # RUNNING ON SEPARATE THREAD!
  4520. def job_init(job_obj, app_obj):
  4521. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  4522. # Propagate options
  4523. job_obj.options["tooldia"] = tooldia
  4524. app_obj.progress.emit(20)
  4525. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  4526. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  4527. app_obj.progress.emit(40)
  4528. job_obj.options['type'] = 'Geometry'
  4529. job_obj.options['tool_dia'] = tooldia
  4530. job_obj.segx = segx
  4531. job_obj.segy = segy
  4532. job_obj.z_pdepth = float(self.options["z_pdepth"])
  4533. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  4534. job_obj.options['xmin'] = self.options['xmin']
  4535. job_obj.options['ymin'] = self.options['ymin']
  4536. job_obj.options['xmax'] = self.options['xmax']
  4537. job_obj.options['ymax'] = self.options['ymax']
  4538. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  4539. # to a value of 0.0005 which is 20 times less than 0.01
  4540. tol = float(self.app.defaults['global_tolerance']) / 20
  4541. job_obj.generate_from_geometry_2(
  4542. self, tooldia=tooldia, offset=offset, tolerance=tol,
  4543. z_cut=z_cut, z_move=z_move,
  4544. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  4545. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  4546. multidepth=multidepth, depthpercut=depthperpass,
  4547. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  4548. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz,
  4549. pp_geometry_name=ppname_g
  4550. )
  4551. app_obj.progress.emit(50)
  4552. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  4553. # source of gcode
  4554. job_obj.toolchange_xy_type = "geometry"
  4555. job_obj.gcode_parse()
  4556. self.app.inform.emit('[success] %s' %
  4557. _("Finished G-Code processing..."))
  4558. app_obj.progress.emit(80)
  4559. if use_thread:
  4560. # To be run in separate thread
  4561. def job_thread(app_obj):
  4562. with self.app.proc_container.new(_("Generating CNC Code")):
  4563. app_obj.new_object("cncjob", outname, job_init, plot=plot)
  4564. app_obj.inform.emit('[success] %s: %s' %
  4565. (_("CNCjob created")), outname)
  4566. app_obj.progress.emit(100)
  4567. # Create a promise with the name
  4568. self.app.collection.promise(outname)
  4569. # Send to worker
  4570. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  4571. else:
  4572. self.app.new_object("cncjob", outname, job_init, plot=plot)
  4573. # def on_plot_cb_click(self, *args): # TODO: args not needed
  4574. # if self.muted_ui:
  4575. # return
  4576. # self.read_form_item('plot')
  4577. def scale(self, xfactor, yfactor=None, point=None):
  4578. """
  4579. Scales all geometry by a given factor.
  4580. :param xfactor: Factor by which to scale the object's geometry/
  4581. :type xfactor: float
  4582. :param yfactor: Factor by which to scale the object's geometry/
  4583. :type yfactor: float
  4584. :return: None
  4585. :rtype: None
  4586. """
  4587. log.debug("FlatCAMObj.FlatCAMGeometry.scale()")
  4588. try:
  4589. xfactor = float(xfactor)
  4590. except Exception:
  4591. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  4592. return
  4593. if yfactor is None:
  4594. yfactor = xfactor
  4595. else:
  4596. try:
  4597. yfactor = float(yfactor)
  4598. except Exception:
  4599. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  4600. return
  4601. if xfactor == 1 and yfactor == 1:
  4602. return
  4603. if point is None:
  4604. px = 0
  4605. py = 0
  4606. else:
  4607. px, py = point
  4608. self.geo_len = 0
  4609. self.old_disp_number = 0
  4610. self.el_count = 0
  4611. def scale_recursion(geom):
  4612. if type(geom) is list:
  4613. geoms = list()
  4614. for local_geom in geom:
  4615. geoms.append(scale_recursion(local_geom))
  4616. return geoms
  4617. else:
  4618. try:
  4619. self.el_count += 1
  4620. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4621. if self.old_disp_number < disp_number <= 100:
  4622. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4623. self.old_disp_number = disp_number
  4624. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  4625. except AttributeError:
  4626. return geom
  4627. if self.multigeo is True:
  4628. for tool in self.tools:
  4629. # variables to display the percentage of work done
  4630. self.geo_len = 0
  4631. try:
  4632. for g in self.tools[tool]['solid_geometry']:
  4633. self.geo_len += 1
  4634. except TypeError:
  4635. self.geo_len = 1
  4636. self.old_disp_number = 0
  4637. self.el_count = 0
  4638. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  4639. try:
  4640. # variables to display the percentage of work done
  4641. self.geo_len = 0
  4642. try:
  4643. self.geo_len = len(self.solid_geometry)
  4644. except TypeError:
  4645. self.geo_len = 1
  4646. self.old_disp_number = 0
  4647. self.el_count = 0
  4648. self.solid_geometry = scale_recursion(self.solid_geometry)
  4649. except AttributeError:
  4650. self.solid_geometry = []
  4651. return
  4652. self.app.proc_container.new_text = ''
  4653. self.app.inform.emit('[success] %s' % _("Geometry Scale done."))
  4654. def offset(self, vect):
  4655. """
  4656. Offsets all geometry by a given vector/
  4657. :param vect: (x, y) vector by which to offset the object's geometry.
  4658. :type vect: tuple
  4659. :return: None
  4660. :rtype: None
  4661. """
  4662. log.debug("FlatCAMObj.FlatCAMGeometry.offset()")
  4663. try:
  4664. dx, dy = vect
  4665. except TypeError:
  4666. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4667. _("An (x,y) pair of values are needed. "
  4668. "Probable you entered only one value in the Offset field.")
  4669. )
  4670. return
  4671. if dx == 0 and dy == 0:
  4672. return
  4673. self.geo_len = 0
  4674. self.old_disp_number = 0
  4675. self.el_count = 0
  4676. def translate_recursion(geom):
  4677. if type(geom) is list:
  4678. geoms = list()
  4679. for local_geom in geom:
  4680. geoms.append(translate_recursion(local_geom))
  4681. return geoms
  4682. else:
  4683. try:
  4684. self.el_count += 1
  4685. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4686. if self.old_disp_number < disp_number <= 100:
  4687. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4688. self.old_disp_number = disp_number
  4689. return affinity.translate(geom, xoff=dx, yoff=dy)
  4690. except AttributeError:
  4691. return geom
  4692. if self.multigeo is True:
  4693. for tool in self.tools:
  4694. # variables to display the percentage of work done
  4695. self.geo_len = 0
  4696. try:
  4697. for g in self.tools[tool]['solid_geometry']:
  4698. self.geo_len += 1
  4699. except TypeError:
  4700. self.geo_len = 1
  4701. self.old_disp_number = 0
  4702. self.el_count = 0
  4703. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  4704. # variables to display the percentage of work done
  4705. self.geo_len = 0
  4706. try:
  4707. for g in self.solid_geometry:
  4708. self.geo_len += 1
  4709. except TypeError:
  4710. self.geo_len = 1
  4711. self.old_disp_number = 0
  4712. self.el_count = 0
  4713. self.solid_geometry = translate_recursion(self.solid_geometry)
  4714. self.app.proc_container.new_text = ''
  4715. self.app.inform.emit('[success] %s' % _("Geometry Offset done."))
  4716. def convert_units(self, units):
  4717. log.debug("FlatCAMObj.FlatCAMGeometry.convert_units()")
  4718. self.ui_disconnect()
  4719. factor = Geometry.convert_units(self, units)
  4720. self.options['cutz'] = float(self.options['cutz']) * factor
  4721. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  4722. self.options['travelz'] = float(self.options['travelz']) * factor
  4723. self.options['feedrate'] = float(self.options['feedrate']) * factor
  4724. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  4725. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  4726. self.options['endz'] = float(self.options['endz']) * factor
  4727. # self.options['cnctooldia'] *= factor
  4728. # self.options['painttooldia'] *= factor
  4729. # self.options['paintmargin'] *= factor
  4730. # self.options['paintoverlap'] *= factor
  4731. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  4732. if self.app.defaults["geometry_toolchangexy"] == '':
  4733. self.options['toolchangexy'] = "0.0, 0.0"
  4734. else:
  4735. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  4736. if len(coords_xy) < 2:
  4737. self.app.inform.emit('[ERROR] %s' %
  4738. _("The Toolchange X,Y field in Edit -> Preferences "
  4739. "has to be in the format (x, y)\n"
  4740. "but now there is only one value, not two.")
  4741. )
  4742. return 'fail'
  4743. coords_xy[0] *= factor
  4744. coords_xy[1] *= factor
  4745. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4746. if self.options['startz'] is not None:
  4747. self.options['startz'] = float(self.options['startz']) * factor
  4748. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4749. 'endz', 'toolchangez']
  4750. if isinstance(self, FlatCAMGeometry):
  4751. temp_tools_dict = {}
  4752. tool_dia_copy = {}
  4753. data_copy = {}
  4754. for tooluid_key, tooluid_value in self.tools.items():
  4755. for dia_key, dia_value in tooluid_value.items():
  4756. if dia_key == 'tooldia':
  4757. dia_value *= factor
  4758. dia_value = float('%.*f' % (self.decimals, dia_value))
  4759. tool_dia_copy[dia_key] = dia_value
  4760. if dia_key == 'offset':
  4761. tool_dia_copy[dia_key] = dia_value
  4762. if dia_key == 'offset_value':
  4763. dia_value *= factor
  4764. tool_dia_copy[dia_key] = dia_value
  4765. # convert the value in the Custom Tool Offset entry in UI
  4766. custom_offset = None
  4767. try:
  4768. custom_offset = float(self.ui.tool_offset_entry.get_value())
  4769. except ValueError:
  4770. # try to convert comma to decimal point. if it's still not working error message and return
  4771. try:
  4772. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  4773. except ValueError:
  4774. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4775. _("Wrong value format entered, use a number."))
  4776. return
  4777. except TypeError:
  4778. pass
  4779. if custom_offset:
  4780. custom_offset *= factor
  4781. self.ui.tool_offset_entry.set_value(custom_offset)
  4782. if dia_key == 'type':
  4783. tool_dia_copy[dia_key] = dia_value
  4784. if dia_key == 'tool_type':
  4785. tool_dia_copy[dia_key] = dia_value
  4786. if dia_key == 'data':
  4787. for data_key, data_value in dia_value.items():
  4788. # convert the form fields that are convertible
  4789. for param in param_list:
  4790. if data_key == param and data_value is not None:
  4791. data_copy[data_key] = data_value * factor
  4792. # copy the other dict entries that are not convertible
  4793. if data_key not in param_list:
  4794. data_copy[data_key] = data_value
  4795. tool_dia_copy[dia_key] = deepcopy(data_copy)
  4796. data_copy.clear()
  4797. temp_tools_dict.update({
  4798. tooluid_key: deepcopy(tool_dia_copy)
  4799. })
  4800. tool_dia_copy.clear()
  4801. self.tools.clear()
  4802. self.tools = deepcopy(temp_tools_dict)
  4803. # if there is a value in the new tool field then convert that one too
  4804. try:
  4805. self.ui.addtool_entry.returnPressed.disconnect()
  4806. except TypeError:
  4807. pass
  4808. tooldia = self.ui.addtool_entry.get_value()
  4809. if tooldia:
  4810. tooldia *= factor
  4811. tooldia = float('%.*f' % (self.decimals, tooldia))
  4812. self.ui.addtool_entry.set_value(tooldia)
  4813. self.ui.addtool_entry.returnPressed.connect(self.on_tool_add)
  4814. return factor
  4815. def plot_element(self, element, color='#FF0000FF', visible=None):
  4816. visible = visible if visible else self.options['plot']
  4817. try:
  4818. for sub_el in element:
  4819. self.plot_element(sub_el)
  4820. except TypeError: # Element is not iterable...
  4821. # if self.app.is_legacy is False:
  4822. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  4823. def plot(self, visible=None, kind=None):
  4824. """
  4825. Plot the object.
  4826. :param visible: Controls if the added shape is visible of not
  4827. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  4828. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  4829. :return:
  4830. """
  4831. # Does all the required setup and returns False
  4832. # if the 'ptint' option is set to False.
  4833. if not FlatCAMObj.plot(self):
  4834. return
  4835. try:
  4836. # plot solid geometries found as members of self.tools attribute dict
  4837. # for MultiGeo
  4838. if self.multigeo is True: # geo multi tool usage
  4839. for tooluid_key in self.tools:
  4840. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4841. self.plot_element(solid_geometry, visible=visible)
  4842. else:
  4843. # plot solid geometry that may be an direct attribute of the geometry object
  4844. # for SingleGeo
  4845. if self.solid_geometry:
  4846. self.plot_element(self.solid_geometry, visible=visible)
  4847. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  4848. self.shapes.redraw()
  4849. except (ObjectDeleted, AttributeError):
  4850. self.shapes.clear(update=True)
  4851. def on_plot_cb_click(self, *args):
  4852. if self.muted_ui:
  4853. return
  4854. self.read_form_item('plot')
  4855. self.plot()
  4856. self.ui_disconnect()
  4857. cb_flag = self.ui.plot_cb.isChecked()
  4858. for row in range(self.ui.geo_tools_table.rowCount()):
  4859. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  4860. if cb_flag:
  4861. table_cb.setChecked(True)
  4862. else:
  4863. table_cb.setChecked(False)
  4864. self.ui_connect()
  4865. def on_plot_cb_click_table(self):
  4866. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4867. self.ui_disconnect()
  4868. # cw = self.sender()
  4869. # cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  4870. # cw_row = cw_index.row()
  4871. check_row = 0
  4872. self.shapes.clear(update=True)
  4873. for tooluid_key in self.tools:
  4874. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  4875. # find the geo_tool_table row associated with the tooluid_key
  4876. for row in range(self.ui.geo_tools_table.rowCount()):
  4877. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  4878. if tooluid_item == int(tooluid_key):
  4879. check_row = row
  4880. break
  4881. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  4882. self.plot_element(element=solid_geometry, visible=True)
  4883. self.shapes.redraw()
  4884. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4885. # if all the row plot's are enabled also enable the general plot checkbox
  4886. cb_cnt = 0
  4887. total_row = self.ui.geo_tools_table.rowCount()
  4888. for row in range(total_row):
  4889. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  4890. cb_cnt += 1
  4891. else:
  4892. cb_cnt -= 1
  4893. if cb_cnt < total_row:
  4894. self.ui.plot_cb.setChecked(False)
  4895. else:
  4896. self.ui.plot_cb.setChecked(True)
  4897. self.ui_connect()
  4898. def merge(self, geo_list, geo_final, multigeo=None):
  4899. """
  4900. Merges the geometry of objects in grb_list into
  4901. the geometry of geo_final.
  4902. :param geo_list: List of FlatCAMGerber Objects to join.
  4903. :param geo_final: Destination FlatCAMGerber object.
  4904. :param multigeo: if the merged geometry objects are of type MultiGeo
  4905. :return: None
  4906. """
  4907. if geo_final.solid_geometry is None:
  4908. geo_final.solid_geometry = []
  4909. if type(geo_final.solid_geometry) is not list:
  4910. geo_final.solid_geometry = [geo_final.solid_geometry]
  4911. for geo in geo_list:
  4912. for option in geo.options:
  4913. if option is not 'name':
  4914. try:
  4915. geo_final.options[option] = deepcopy(geo.options[option])
  4916. except Exception as e:
  4917. log.warning("Failed to copy option %s. Error: %s" % (str(option), str(e)))
  4918. # Expand lists
  4919. if type(geo) is list:
  4920. FlatCAMGeometry.merge(self, geo_list=geo, geo_final=geo_final)
  4921. # If not list, just append
  4922. else:
  4923. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  4924. if multigeo is None or multigeo is False:
  4925. geo_final.multigeo = False
  4926. try:
  4927. geo_final.solid_geometry.append(deepcopy(geo.solid_geometry))
  4928. except Exception as e:
  4929. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  4930. else:
  4931. geo_final.multigeo = True
  4932. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  4933. # tools object attribute, as a key value
  4934. geo_final.solid_geometry = []
  4935. # find the tool_uid maximum value in the geo_final
  4936. geo_final_uid_list = []
  4937. for key in geo_final.tools:
  4938. geo_final_uid_list.append(int(key))
  4939. try:
  4940. max_uid = max(geo_final_uid_list, key=int)
  4941. except ValueError:
  4942. max_uid = 0
  4943. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  4944. # to merge the obj.tools as it is likely there is none to merge.
  4945. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  4946. for tool_uid in geo.tools:
  4947. max_uid += 1
  4948. geo_final.tools[max_uid] = deepcopy(geo.tools[tool_uid])
  4949. @staticmethod
  4950. def get_pts(o):
  4951. """
  4952. Returns a list of all points in the object, where
  4953. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  4954. of such. Search is done recursively.
  4955. :param: geometric object
  4956. :return: List of points
  4957. :rtype: list
  4958. """
  4959. pts = []
  4960. # Iterable: descend into each item.
  4961. try:
  4962. for subo in o:
  4963. pts += FlatCAMGeometry.get_pts(subo)
  4964. # Non-iterable
  4965. except TypeError:
  4966. if o is not None:
  4967. if type(o) == MultiPolygon:
  4968. for poly in o:
  4969. pts += FlatCAMGeometry.get_pts(poly)
  4970. # ## Descend into .exerior and .interiors
  4971. elif type(o) == Polygon:
  4972. pts += FlatCAMGeometry.get_pts(o.exterior)
  4973. for i in o.interiors:
  4974. pts += FlatCAMGeometry.get_pts(i)
  4975. elif type(o) == MultiLineString:
  4976. for line in o:
  4977. pts += FlatCAMGeometry.get_pts(line)
  4978. # ## Has .coords: list them.
  4979. else:
  4980. pts += list(o.coords)
  4981. else:
  4982. return
  4983. return pts
  4984. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  4985. """
  4986. Represents G-Code.
  4987. """
  4988. optionChanged = QtCore.pyqtSignal(str)
  4989. ui_type = CNCObjectUI
  4990. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  4991. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  4992. spindlespeed=None):
  4993. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  4994. self.decimals = self.app.decimals
  4995. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  4996. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  4997. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  4998. FlatCAMObj.__init__(self, name)
  4999. self.kind = "cncjob"
  5000. self.options.update({
  5001. "plot": True,
  5002. "tooldia": 0.03937, # 0.4mm in inches
  5003. "append": "",
  5004. "prepend": "",
  5005. "dwell": False,
  5006. "dwelltime": 1,
  5007. "type": 'Geometry',
  5008. "toolchange_macro": '',
  5009. "toolchange_macro_enable": False
  5010. })
  5011. '''
  5012. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  5013. diameter of the tools and the value is another dict that will hold the data under the following form:
  5014. {tooldia: {
  5015. 'tooluid': 1,
  5016. 'offset': 'Path',
  5017. 'type_item': 'Rough',
  5018. 'tool_type': 'C1',
  5019. 'data': {} # a dict to hold the parameters
  5020. 'gcode': "" # a string with the actual GCODE
  5021. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry
  5022. (cut or move)
  5023. 'solid_geometry': []
  5024. },
  5025. ...
  5026. }
  5027. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  5028. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  5029. '''
  5030. self.cnc_tools = dict()
  5031. '''
  5032. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  5033. diameter of the tools and the value is another dict that will hold the data under the following form:
  5034. {tooldia: {
  5035. 'tool': int,
  5036. 'nr_drills': int,
  5037. 'nr_slots': int,
  5038. 'offset': float,
  5039. 'data': {} # a dict to hold the parameters
  5040. 'gcode': "" # a string with the actual GCODE
  5041. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  5042. 'solid_geometry': []
  5043. },
  5044. ...
  5045. }
  5046. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  5047. it's done in camlib.CNCJob.generate_from_excellon_by_tool()
  5048. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  5049. '''
  5050. self.exc_cnc_tools = dict()
  5051. # flag to store if the CNCJob is part of a special group of CNCJob objects that can't be processed by the
  5052. # default engine of FlatCAM. They generated by some of tools and are special cases of CNCJob objects.
  5053. self.special_group = None
  5054. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  5055. # (like the one in the TCL Command), False
  5056. self.multitool = False
  5057. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  5058. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  5059. self.g_x_re = re.compile(gcodex_re_string)
  5060. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  5061. self.g_y_re = re.compile(gcodey_re_string)
  5062. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  5063. self.g_z_re = re.compile(gcodez_re_string)
  5064. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  5065. self.g_f_re = re.compile(gcodef_re_string)
  5066. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  5067. self.g_t_re = re.compile(gcodet_re_string)
  5068. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  5069. self.g_nr_re = re.compile(gcodenr_re_string)
  5070. # Attributes to be included in serialization
  5071. # Always append to it because it carries contents
  5072. # from predecessors.
  5073. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  5074. if self.app.is_legacy is False:
  5075. self.text_col = self.app.plotcanvas.new_text_collection()
  5076. self.text_col.enabled = True
  5077. self.annotation = self.app.plotcanvas.new_text_group(collection=self.text_col)
  5078. self.gcode_editor_tab = None
  5079. self.units_found = self.app.defaults['units']
  5080. def build_ui(self):
  5081. self.ui_disconnect()
  5082. FlatCAMObj.build_ui(self)
  5083. self.units = self.app.defaults['units'].upper()
  5084. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  5085. self.ui.cnc_tools_table.hide()
  5086. if self.cnc_tools:
  5087. self.ui.cnc_tools_table.show()
  5088. self.build_cnc_tools_table()
  5089. self.ui.exc_cnc_tools_table.hide()
  5090. if self.exc_cnc_tools:
  5091. self.ui.exc_cnc_tools_table.show()
  5092. self.build_excellon_cnc_tools()
  5093. #
  5094. self.ui_connect()
  5095. def build_cnc_tools_table(self):
  5096. offset = 0
  5097. tool_idx = 0
  5098. n = len(self.cnc_tools)
  5099. self.ui.cnc_tools_table.setRowCount(n)
  5100. for dia_key, dia_value in self.cnc_tools.items():
  5101. tool_idx += 1
  5102. row_no = tool_idx - 1
  5103. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  5104. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  5105. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  5106. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  5107. # There are no tool bits in MM with more than 2 decimals diameter.
  5108. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  5109. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['tooldia'])))
  5110. offset_txt = list(str(dia_value['offset']))
  5111. offset_txt[0] = offset_txt[0].upper()
  5112. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  5113. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  5114. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  5115. id.setFlags(QtCore.Qt.ItemIsEnabled)
  5116. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5117. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5118. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5119. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5120. # hack so the checkbox stay centered in the table cell
  5121. # used this:
  5122. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  5123. # plot_item = QtWidgets.QWidget()
  5124. # checkbox = FCCheckBox()
  5125. # checkbox.setCheckState(QtCore.Qt.Checked)
  5126. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  5127. # qhboxlayout.addWidget(checkbox)
  5128. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  5129. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  5130. plot_item = FCCheckBox()
  5131. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  5132. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  5133. if self.ui.plot_cb.isChecked():
  5134. plot_item.setChecked(True)
  5135. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  5136. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  5137. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  5138. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  5139. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  5140. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  5141. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  5142. # make the diameter column editable
  5143. # for row in range(tool_idx):
  5144. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  5145. # QtCore.Qt.ItemIsEnabled)
  5146. for row in range(tool_idx):
  5147. self.ui.cnc_tools_table.item(row, 0).setFlags(
  5148. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  5149. self.ui.cnc_tools_table.resizeColumnsToContents()
  5150. self.ui.cnc_tools_table.resizeRowsToContents()
  5151. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  5152. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  5153. vertical_header.hide()
  5154. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5155. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  5156. horizontal_header.setMinimumSectionSize(10)
  5157. horizontal_header.setDefaultSectionSize(70)
  5158. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  5159. horizontal_header.resizeSection(0, 20)
  5160. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  5161. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  5162. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  5163. horizontal_header.resizeSection(4, 40)
  5164. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  5165. horizontal_header.resizeSection(4, 17)
  5166. # horizontal_header.setStretchLastSection(True)
  5167. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5168. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  5169. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  5170. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  5171. # self.ui.geo_tools_table.setSortingEnabled(True)
  5172. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  5173. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  5174. def build_excellon_cnc_tools(self):
  5175. tool_idx = 0
  5176. n = len(self.exc_cnc_tools)
  5177. self.ui.exc_cnc_tools_table.setRowCount(n)
  5178. for tooldia_key, dia_value in self.exc_cnc_tools.items():
  5179. tool_idx += 1
  5180. row_no = tool_idx - 1
  5181. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  5182. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooldia_key)))
  5183. nr_drills_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_drills']))
  5184. nr_slots_item = QtWidgets.QTableWidgetItem('%d' % int(dia_value['nr_slots']))
  5185. cutz_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(dia_value['offset_z']) + self.z_cut))
  5186. id.setFlags(QtCore.Qt.ItemIsEnabled)
  5187. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5188. nr_drills_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5189. nr_slots_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5190. cutz_item.setFlags(QtCore.Qt.ItemIsEnabled)
  5191. # hack so the checkbox stay centered in the table cell
  5192. # used this:
  5193. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  5194. # plot_item = QtWidgets.QWidget()
  5195. # checkbox = FCCheckBox()
  5196. # checkbox.setCheckState(QtCore.Qt.Checked)
  5197. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  5198. # qhboxlayout.addWidget(checkbox)
  5199. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  5200. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  5201. plot_item = FCCheckBox()
  5202. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  5203. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_value['tool']))
  5204. if self.ui.plot_cb.isChecked():
  5205. plot_item.setChecked(True)
  5206. # TODO until the feature of individual plot for an Excellon tool is implemented
  5207. plot_item.setDisabled(True)
  5208. self.ui.exc_cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  5209. self.ui.exc_cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  5210. self.ui.exc_cnc_tools_table.setItem(row_no, 2, nr_drills_item) # Nr of drills
  5211. self.ui.exc_cnc_tools_table.setItem(row_no, 3, nr_slots_item) # Nr of slots
  5212. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  5213. self.ui.exc_cnc_tools_table.setItem(row_no, 4, tool_uid_item) # Tool unique ID)
  5214. self.ui.exc_cnc_tools_table.setItem(row_no, 5, cutz_item)
  5215. self.ui.exc_cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  5216. for row in range(tool_idx):
  5217. self.ui.exc_cnc_tools_table.item(row, 0).setFlags(
  5218. self.ui.exc_cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  5219. self.ui.exc_cnc_tools_table.resizeColumnsToContents()
  5220. self.ui.exc_cnc_tools_table.resizeRowsToContents()
  5221. vertical_header = self.ui.exc_cnc_tools_table.verticalHeader()
  5222. vertical_header.hide()
  5223. self.ui.exc_cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5224. horizontal_header = self.ui.exc_cnc_tools_table.horizontalHeader()
  5225. horizontal_header.setMinimumSectionSize(10)
  5226. horizontal_header.setDefaultSectionSize(70)
  5227. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  5228. horizontal_header.resizeSection(0, 20)
  5229. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  5230. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  5231. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  5232. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
  5233. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  5234. # horizontal_header.setStretchLastSection(True)
  5235. self.ui.exc_cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  5236. self.ui.exc_cnc_tools_table.setColumnWidth(0, 20)
  5237. self.ui.exc_cnc_tools_table.setColumnWidth(6, 17)
  5238. self.ui.exc_cnc_tools_table.setMinimumHeight(self.ui.exc_cnc_tools_table.getHeight())
  5239. self.ui.exc_cnc_tools_table.setMaximumHeight(self.ui.exc_cnc_tools_table.getHeight())
  5240. def set_ui(self, ui):
  5241. FlatCAMObj.set_ui(self, ui)
  5242. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  5243. assert isinstance(self.ui, CNCObjectUI), \
  5244. "Expected a CNCObjectUI, got %s" % type(self.ui)
  5245. self.units = self.app.defaults['units'].upper()
  5246. self.units_found = self.app.defaults['units']
  5247. # this signal has to be connected to it's slot before the defaults are populated
  5248. # the decision done in the slot has to override the default value set bellow
  5249. self.ui.toolchange_cb.toggled.connect(self.on_toolchange_custom_clicked)
  5250. self.form_fields.update({
  5251. "plot": self.ui.plot_cb,
  5252. "tooldia": self.ui.tooldia_entry,
  5253. "append": self.ui.append_text,
  5254. "prepend": self.ui.prepend_text,
  5255. "toolchange_macro": self.ui.toolchange_text,
  5256. "toolchange_macro_enable": self.ui.toolchange_cb
  5257. })
  5258. # Fill form fields only on object create
  5259. self.to_form()
  5260. # this means that the object that created this CNCJob was an Excellon or Geometry
  5261. try:
  5262. if self.travel_distance:
  5263. self.ui.t_distance_label.show()
  5264. self.ui.t_distance_entry.setVisible(True)
  5265. self.ui.t_distance_entry.setDisabled(True)
  5266. self.ui.t_distance_entry.set_value('%.*f' % (self.decimals, float(self.travel_distance)))
  5267. self.ui.units_label.setText(str(self.units).lower())
  5268. self.ui.units_label.setDisabled(True)
  5269. self.ui.t_time_label.show()
  5270. self.ui.t_time_entry.setVisible(True)
  5271. self.ui.t_time_entry.setDisabled(True)
  5272. # if time is more than 1 then we have minutes, else we have seconds
  5273. if self.routing_time > 1:
  5274. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(self.routing_time))))
  5275. self.ui.units_time_label.setText('min')
  5276. else:
  5277. time_r = self.routing_time * 60
  5278. self.ui.t_time_entry.set_value('%.*f' % (self.decimals, math.ceil(float(time_r))))
  5279. self.ui.units_time_label.setText('sec')
  5280. self.ui.units_time_label.setDisabled(True)
  5281. except AttributeError:
  5282. pass
  5283. if self.multitool is False:
  5284. self.ui.tooldia_entry.show()
  5285. self.ui.updateplot_button.show()
  5286. else:
  5287. self.ui.tooldia_entry.hide()
  5288. self.ui.updateplot_button.hide()
  5289. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  5290. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  5291. try:
  5292. self.ui.annotation_cb.stateChanged.disconnect(self.on_annotation_change)
  5293. except (TypeError, AttributeError):
  5294. pass
  5295. self.ui.annotation_cb.stateChanged.connect(self.on_annotation_change)
  5296. # set if to display text annotations
  5297. self.ui.annotation_cb.set_value(self.app.defaults["cncjob_annotation"])
  5298. # Show/Hide Advanced Options
  5299. if self.app.defaults["global_app_level"] == 'b':
  5300. self.ui.level.setText(_(
  5301. '<span style="color:green;"><b>Basic</b></span>'
  5302. ))
  5303. self.ui.cnc_frame.hide()
  5304. else:
  5305. self.ui.level.setText(_(
  5306. '<span style="color:red;"><b>Advanced</b></span>'
  5307. ))
  5308. self.ui.cnc_frame.show()
  5309. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  5310. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  5311. self.ui.modify_gcode_button.clicked.connect(self.on_edit_code_click)
  5312. self.ui.tc_variable_combo.currentIndexChanged[str].connect(self.on_cnc_custom_parameters)
  5313. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  5314. def on_cnc_custom_parameters(self, signal_text):
  5315. if signal_text == 'Parameters':
  5316. return
  5317. else:
  5318. self.ui.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5319. def ui_connect(self):
  5320. for row in range(self.ui.cnc_tools_table.rowCount()):
  5321. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  5322. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  5323. def ui_disconnect(self):
  5324. for row in range(self.ui.cnc_tools_table.rowCount()):
  5325. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  5326. try:
  5327. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  5328. except (TypeError, AttributeError):
  5329. pass
  5330. def on_updateplot_button_click(self, *args):
  5331. """
  5332. Callback for the "Updata Plot" button. Reads the form for updates
  5333. and plots the object.
  5334. """
  5335. self.read_form()
  5336. self.on_plot_kind_change()
  5337. def on_plot_kind_change(self):
  5338. kind = self.ui.cncplot_method_combo.get_value()
  5339. def worker_task():
  5340. with self.app.proc_container.new(_("Plotting...")):
  5341. self.plot(kind=kind)
  5342. self.app.worker_task.emit({'fcn': worker_task, 'params': []})
  5343. def on_exportgcode_button_click(self, *args):
  5344. self.app.report_usage("cncjob_on_exportgcode_button")
  5345. self.read_form()
  5346. name = self.app.collection.get_active().options['name']
  5347. save_gcode = False
  5348. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5349. _filter_ = "RML1 Files (*.rol);;All Files (*.*)"
  5350. elif 'hpgl' in self.pp_geometry_name:
  5351. _filter_ = "HPGL Files (*.plt);;All Files (*.*)"
  5352. else:
  5353. save_gcode = True
  5354. _filter_ = self.app.defaults['cncjob_save_filters']
  5355. try:
  5356. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  5357. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5358. caption=_("Export Machine Code ..."),
  5359. directory=dir_file_to_save,
  5360. filter=_filter_
  5361. )
  5362. except TypeError:
  5363. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Machine Code ..."), filter=_filter_)
  5364. filename = str(filename)
  5365. if filename == '':
  5366. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Export Machine Code cancelled ..."))
  5367. return
  5368. else:
  5369. if save_gcode is True:
  5370. used_extension = filename.rpartition('.')[2]
  5371. self.update_filters(last_ext=used_extension, filter_string='cncjob_save_filters')
  5372. new_name = os.path.split(str(filename))[1].rpartition('.')[0]
  5373. self.ui.name_entry.set_value(new_name)
  5374. self.on_name_activate(silent=True)
  5375. preamble = str(self.ui.prepend_text.get_value())
  5376. postamble = str(self.ui.append_text.get_value())
  5377. gc = self.export_gcode(filename, preamble=preamble, postamble=postamble)
  5378. if gc == 'fail':
  5379. return
  5380. if self.app.defaults["global_open_style"] is False:
  5381. self.app.file_opened.emit("gcode", filename)
  5382. self.app.file_saved.emit("gcode", filename)
  5383. self.app.inform.emit('[success] %s: %s' %
  5384. (_("Machine Code file saved to"), filename))
  5385. def on_edit_code_click(self, *args):
  5386. self.app.proc_container.view.set_busy(_("Loading..."))
  5387. preamble = str(self.ui.prepend_text.get_value())
  5388. postamble = str(self.ui.append_text.get_value())
  5389. gco = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  5390. if gco == 'fail':
  5391. return
  5392. else:
  5393. self.app.gcode_edited = gco
  5394. self.gcode_editor_tab = TextEditor(app=self.app, plain_text=True)
  5395. # add the tab if it was closed
  5396. self.app.ui.plot_tab_area.addTab(self.gcode_editor_tab, '%s' % _("Code Editor"))
  5397. self.gcode_editor_tab.setObjectName('code_editor_tab')
  5398. # delete the absolute and relative position and messages in the infobar
  5399. self.app.ui.position_label.setText("")
  5400. self.app.ui.rel_position_label.setText("")
  5401. # first clear previous text in text editor (if any)
  5402. self.gcode_editor_tab.code_editor.clear()
  5403. self.gcode_editor_tab.code_editor.setReadOnly(False)
  5404. self.gcode_editor_tab.code_editor.completer_enable = False
  5405. self.gcode_editor_tab.buttonRun.hide()
  5406. # Switch plot_area to CNCJob tab
  5407. self.app.ui.plot_tab_area.setCurrentWidget(self.gcode_editor_tab)
  5408. self.gcode_editor_tab.t_frame.hide()
  5409. # then append the text from GCode to the text editor
  5410. try:
  5411. self.gcode_editor_tab.code_editor.setPlainText(self.app.gcode_edited.getvalue())
  5412. # for line in self.app.gcode_edited:
  5413. # QtWidgets.QApplication.processEvents()
  5414. #
  5415. # proc_line = str(line).strip('\n')
  5416. # self.gcode_editor_tab.code_editor.append(proc_line)
  5417. except Exception as e:
  5418. log.debug('FlatCAMCNNJob.on_edit_code_click() -->%s' % str(e))
  5419. self.app.inform.emit('[ERROR] %s %s' % ('FlatCAMCNNJob.on_edit_code_click() -->', str(e)))
  5420. return
  5421. self.gcode_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5422. self.gcode_editor_tab.handleTextChanged()
  5423. self.gcode_editor_tab.t_frame.show()
  5424. self.app.proc_container.view.set_idle()
  5425. self.app.inform.emit('[success] %s...' % _('Loaded Machine Code into Code Editor'))
  5426. def gcode_header(self, comment_start_symbol=None, comment_stop_symbol=None):
  5427. """
  5428. Will create a header to be added to all GCode files generated by FlatCAM
  5429. :param comment_start_symbol: a symbol to be used as the first symbol in a comment
  5430. :param comment_stop_symbol: a symbol to be used as the last symbol in a comment
  5431. :return: a string with a GCode header
  5432. """
  5433. log.debug("FlatCAMCNCJob.gcode_header()")
  5434. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5435. marlin = False
  5436. hpgl = False
  5437. probe_pp = False
  5438. start_comment = comment_start_symbol if comment_start_symbol is not None else '('
  5439. stop_comment = comment_stop_symbol if comment_stop_symbol is not None else ')'
  5440. try:
  5441. for key in self.cnc_tools:
  5442. ppg = self.cnc_tools[key]['data']['ppname_g']
  5443. if ppg == 'marlin' or ppg == 'Repetier':
  5444. marlin = True
  5445. break
  5446. if ppg == 'hpgl':
  5447. hpgl = True
  5448. break
  5449. if "toolchange_probe" in ppg.lower():
  5450. probe_pp = True
  5451. break
  5452. except KeyError:
  5453. # log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  5454. pass
  5455. try:
  5456. if self.options['ppname_e'] == 'marlin' or self.options['ppname_e'] == 'Repetier':
  5457. marlin = True
  5458. except KeyError:
  5459. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  5460. pass
  5461. try:
  5462. if "toolchange_probe" in self.options['ppname_e'].lower():
  5463. probe_pp = True
  5464. except KeyError:
  5465. # log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  5466. pass
  5467. if marlin is True:
  5468. gcode = ';Marlin(Repetier) G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5469. (str(self.app.version), str(self.app.version_date)) + '\n'
  5470. gcode += ';Name: ' + str(self.options['name']) + '\n'
  5471. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  5472. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5473. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5474. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  5475. gcode += ';Created on ' + time_str + '\n' + '\n'
  5476. elif hpgl is True:
  5477. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  5478. (str(self.app.version), str(self.app.version_date)) + '";\n'
  5479. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  5480. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  5481. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5482. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5483. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  5484. gcode += 'CO "Created on ' + time_str + '";\n'
  5485. elif probe_pp is True:
  5486. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  5487. (str(self.app.version), str(self.app.version_date)) + '\n'
  5488. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  5489. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  5490. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  5491. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  5492. 'Then zero the Z axis.)\n' + '\n'
  5493. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  5494. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  5495. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5496. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5497. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  5498. gcode += '(Created on ' + time_str + ')\n' + '\n'
  5499. else:
  5500. gcode = '%sG-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s%s\n' % \
  5501. (start_comment, str(self.app.version), str(self.app.version_date), stop_comment) + '\n'
  5502. gcode += '%sName: ' % start_comment + str(self.options['name']) + '%s\n' % stop_comment
  5503. gcode += '%sType: ' % start_comment + "G-code from " + str(self.options['type']) + '%s\n' % stop_comment
  5504. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  5505. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  5506. gcode += '%sUnits: ' % start_comment + self.units.upper() + '%s\n' % stop_comment + "\n"
  5507. gcode += '%sCreated on ' % start_comment + time_str + '%s\n' % stop_comment + '\n'
  5508. return gcode
  5509. def gcode_footer(self, end_command=None):
  5510. """
  5511. :param end_command: 'M02' or 'M30' - String
  5512. :return:
  5513. """
  5514. if end_command:
  5515. return end_command
  5516. else:
  5517. return 'M02'
  5518. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  5519. """
  5520. This will save the GCode from the Gcode object to a file on the OS filesystem
  5521. :param filename: filename for the GCode file
  5522. :param preamble: a custom Gcode block to be added at the beginning of the Gcode file
  5523. :param postamble: a custom Gcode block to be added at the end of the Gcode file
  5524. :param to_file: if False then no actual file is saved but the app will know that a file was created
  5525. :return: None
  5526. """
  5527. # gcode = ''
  5528. # roland = False
  5529. # hpgl = False
  5530. # isel_icp = False
  5531. include_header = True
  5532. try:
  5533. if self.special_group:
  5534. self.app.inform.emit('[WARNING_NOTCL] %s %s %s.' %
  5535. (_("This CNCJob object can't be processed because it is a"),
  5536. str(self.special_group),
  5537. _("CNCJob object")))
  5538. return 'fail'
  5539. except AttributeError:
  5540. pass
  5541. # if this dict is not empty then the object is a Geometry object
  5542. if self.cnc_tools:
  5543. first_key = next(iter(self.cnc_tools))
  5544. include_header = self.app.preprocessors[self.cnc_tools[first_key]['data']['ppname_g']].include_header
  5545. # if this dict is not empty then the object is an Excellon object
  5546. if self.exc_cnc_tools:
  5547. first_key = next(iter(self.exc_cnc_tools))
  5548. include_header = self.app.preprocessors[self.exc_cnc_tools[first_key]['data']['ppname_e']].include_header
  5549. # # detect if using Roland preprocessor
  5550. # try:
  5551. # for key in self.cnc_tools:
  5552. # if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  5553. # roland = True
  5554. # break
  5555. # except Exception:
  5556. # try:
  5557. # for key in self.cnc_tools:
  5558. # if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  5559. # roland = True
  5560. # break
  5561. # except Exception:
  5562. # pass
  5563. #
  5564. # # detect if using HPGL preprocessor
  5565. # try:
  5566. # for key in self.cnc_tools:
  5567. # if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  5568. # hpgl = True
  5569. # break
  5570. # except Exception:
  5571. # try:
  5572. # for key in self.cnc_tools:
  5573. # if self.cnc_tools[key]['data']['ppname_e'] == 'hpgl':
  5574. # hpgl = True
  5575. # break
  5576. # except Exception:
  5577. # pass
  5578. #
  5579. # # detect if using ISEL_ICP_CNC preprocessor
  5580. # try:
  5581. # for key in self.cnc_tools:
  5582. # if 'ISEL_ICP' in self.cnc_tools[key]['data']['ppname_g'].upper():
  5583. # isel_icp = True
  5584. # break
  5585. # except Exception:
  5586. # try:
  5587. # for key in self.cnc_tools:
  5588. # if 'ISEL_ICP' in self.cnc_tools[key]['data']['ppname_e'].upper():
  5589. # isel_icp = True
  5590. # break
  5591. # except Exception:
  5592. # pass
  5593. # do not add gcode_header when using the Roland preprocessor, add it for every other preprocessor
  5594. # if roland is False and hpgl is False and isel_icp is False:
  5595. # gcode = self.gcode_header()
  5596. # do not add gcode_header when using the Roland, HPGL or ISEP_ICP_CNC preprocessor (or any other preprocessor
  5597. # that has the include_header attribute set as False, add it for every other preprocessor
  5598. # if include_header:
  5599. # gcode = self.gcode_header()
  5600. # else:
  5601. # gcode = ''
  5602. # # detect if using multi-tool and make the Gcode summation correctly for each case
  5603. # if self.multitool is True:
  5604. # for tooluid_key in self.cnc_tools:
  5605. # for key, value in self.cnc_tools[tooluid_key].items():
  5606. # if key == 'gcode':
  5607. # gcode += value
  5608. # break
  5609. # else:
  5610. # gcode += self.gcode
  5611. # if roland is True:
  5612. # g = preamble + gcode + postamble
  5613. # elif hpgl is True:
  5614. # g = self.gcode_header() + preamble + gcode + postamble
  5615. # else:
  5616. # # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  5617. # g_idx = gcode.rfind('G20')
  5618. #
  5619. # # if it did not find 'G20' then search for 'G21'
  5620. # if g_idx == -1:
  5621. # g_idx = gcode.rfind('G21')
  5622. #
  5623. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  5624. # # but only when the preprocessor is not ISEL_ICP who is allowed not to have the G20/G21 command
  5625. # if g_idx == -1 and isel_icp is False:
  5626. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  5627. # return
  5628. #
  5629. # footer = self.app.defaults['cncjob_footer']
  5630. # end_gcode = self.gcode_footer() if footer is True else ''
  5631. # g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble + end_gcode
  5632. gcode = ''
  5633. if include_header is False:
  5634. g = preamble
  5635. # detect if using multi-tool and make the Gcode summation correctly for each case
  5636. if self.multitool is True:
  5637. for tooluid_key in self.cnc_tools:
  5638. for key, value in self.cnc_tools[tooluid_key].items():
  5639. if key == 'gcode':
  5640. gcode += value
  5641. break
  5642. else:
  5643. gcode += self.gcode
  5644. g = g + gcode + postamble
  5645. else:
  5646. # search for the GCode beginning which is usually a G20 or G21
  5647. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  5648. # g_idx = gcode.rfind('G20')
  5649. #
  5650. # # if it did not find 'G20' then search for 'G21'
  5651. # if g_idx == -1:
  5652. # g_idx = gcode.rfind('G21')
  5653. #
  5654. # # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  5655. # if g_idx == -1:
  5656. # self.app.inform.emit('[ERROR_NOTCL] %s' % _("G-code does not have a units code: either G20 or G21"))
  5657. # return
  5658. # detect if using multi-tool and make the Gcode summation correctly for each case
  5659. if self.multitool is True:
  5660. for tooluid_key in self.cnc_tools:
  5661. for key, value in self.cnc_tools[tooluid_key].items():
  5662. if key == 'gcode':
  5663. gcode += value
  5664. break
  5665. else:
  5666. gcode += self.gcode
  5667. end_gcode = self.gcode_footer() if self.app.defaults['cncjob_footer'] is True else ''
  5668. # detect if using a HPGL preprocessor
  5669. hpgl = False
  5670. if self.cnc_tools:
  5671. for key in self.cnc_tools:
  5672. if 'ppname_g' in self.cnc_tools[key]['data']:
  5673. if 'hpgl' in self.cnc_tools[key]['data']['ppname_g']:
  5674. hpgl = True
  5675. break
  5676. elif self.exc_cnc_tools:
  5677. for key in self.cnc_tools:
  5678. if 'ppname_e' in self.cnc_tools[key]['data']:
  5679. if 'hpgl' in self.cnc_tools[key]['data']['ppname_e']:
  5680. hpgl = True
  5681. break
  5682. if hpgl:
  5683. processed_gcode = ''
  5684. pa_re = re.compile(r"^PA\s*(-?\d+\.\d*),?\s*(-?\d+\.\d*)*;?$")
  5685. for gline in gcode.splitlines():
  5686. match = pa_re.search(gline)
  5687. if match:
  5688. x_int = int(float(match.group(1)))
  5689. y_int = int(float(match.group(2)))
  5690. new_line = 'PA%d,%d;\n' % (x_int, y_int)
  5691. processed_gcode += new_line
  5692. else:
  5693. processed_gcode += gline + '\n'
  5694. gcode = processed_gcode
  5695. g = self.gcode_header() + '\n' + preamble + '\n' + gcode + postamble + end_gcode
  5696. else:
  5697. try:
  5698. g_idx = gcode.index('G94')
  5699. g = self.gcode_header() + gcode[:g_idx + 3] + '\n\n' + preamble + '\n' + \
  5700. gcode[(g_idx + 3):] + postamble + end_gcode
  5701. except ValueError:
  5702. self.app.inform.emit('[ERROR_NOTCL] %s' %
  5703. _("G-code does not have a G94 code and we will not include the code in the "
  5704. "'Prepend to GCode' text box"))
  5705. g = self.gcode_header() + '\n' + gcode + postamble + end_gcode
  5706. # if toolchange custom is used, replace M6 code with the code from the Toolchange Custom Text box
  5707. if self.ui.toolchange_cb.get_value() is True:
  5708. # match = self.re_toolchange.search(g)
  5709. if 'M6' in g:
  5710. m6_code = self.parse_custom_toolchange_code(self.ui.toolchange_text.get_value())
  5711. if m6_code is None or m6_code == '':
  5712. self.app.inform.emit(
  5713. '[ERROR_NOTCL] %s' % _("Cancelled. The Toolchange Custom code is enabled but it's empty.")
  5714. )
  5715. return 'fail'
  5716. g = g.replace('M6', m6_code)
  5717. self.app.inform.emit('[success] %s' % _("Toolchange G-code was replaced by a custom code."))
  5718. lines = StringIO(g)
  5719. # Write
  5720. if filename is not None:
  5721. try:
  5722. force_windows_line_endings = self.app.defaults['cncjob_line_ending']
  5723. if force_windows_line_endings and sys.platform != 'win32':
  5724. with open(filename, 'w', newline='\r\n') as f:
  5725. for line in lines:
  5726. f.write(line)
  5727. else:
  5728. with open(filename, 'w') as f:
  5729. for line in lines:
  5730. f.write(line)
  5731. except FileNotFoundError:
  5732. self.app.inform.emit('[WARNING_NOTCL] %s' % _("No such file or directory"))
  5733. return
  5734. except PermissionError:
  5735. self.app.inform.emit(
  5736. '[WARNING] %s' % _("Permission denied, saving not possible.\n"
  5737. "Most likely another app is holding the file open and not accessible.")
  5738. )
  5739. return 'fail'
  5740. elif to_file is False:
  5741. # Just for adding it to the recent files list.
  5742. if self.app.defaults["global_open_style"] is False:
  5743. self.app.file_opened.emit("cncjob", filename)
  5744. self.app.file_saved.emit("cncjob", filename)
  5745. self.app.inform.emit('[success] %s: %s' % (_("Saved to"), filename))
  5746. else:
  5747. return lines
  5748. def on_toolchange_custom_clicked(self, signal):
  5749. try:
  5750. if 'toolchange_custom' not in str(self.options['ppname_e']).lower():
  5751. if self.ui.toolchange_cb.get_value():
  5752. self.ui.toolchange_cb.set_value(False)
  5753. self.app.inform.emit('[WARNING_NOTCL] %s' %
  5754. _("The used preprocessor file has to have in it's name: 'toolchange_custom'"))
  5755. except KeyError:
  5756. try:
  5757. for key in self.cnc_tools:
  5758. ppg = self.cnc_tools[key]['data']['ppname_g']
  5759. if 'toolchange_custom' not in str(ppg).lower():
  5760. print(ppg)
  5761. if self.ui.toolchange_cb.get_value():
  5762. self.ui.toolchange_cb.set_value(False)
  5763. self.app.inform.emit('[WARNING_NOTCL] %s' %
  5764. _("The used preprocessor file has to have in it's name: "
  5765. "'toolchange_custom'"))
  5766. except KeyError:
  5767. self.app.inform.emit('[ERROR] %s' %
  5768. _("There is no preprocessor file."))
  5769. def get_gcode(self, preamble='', postamble=''):
  5770. # we need this to be able get_gcode separatelly for shell command export_gcode
  5771. return preamble + '\n' + self.gcode + "\n" + postamble
  5772. def get_svg(self):
  5773. # we need this to be able get_svg separately for shell command export_svg
  5774. pass
  5775. def on_plot_cb_click(self, *args):
  5776. if self.muted_ui:
  5777. return
  5778. kind = self.ui.cncplot_method_combo.get_value()
  5779. self.plot(kind=kind)
  5780. self.read_form_item('plot')
  5781. self.ui_disconnect()
  5782. cb_flag = self.ui.plot_cb.isChecked()
  5783. for row in range(self.ui.cnc_tools_table.rowCount()):
  5784. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  5785. if cb_flag:
  5786. table_cb.setChecked(True)
  5787. else:
  5788. table_cb.setChecked(False)
  5789. self.ui_connect()
  5790. def on_plot_cb_click_table(self):
  5791. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  5792. self.ui_disconnect()
  5793. # cw = self.sender()
  5794. # cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  5795. # cw_row = cw_index.row()
  5796. kind = self.ui.cncplot_method_combo.get_value()
  5797. self.shapes.clear(update=True)
  5798. for tooluid_key in self.cnc_tools:
  5799. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  5800. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  5801. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  5802. for r in range(self.ui.cnc_tools_table.rowCount()):
  5803. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  5804. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  5805. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed, kind=kind)
  5806. self.shapes.redraw()
  5807. # make sure that the general plot is disabled if one of the row plot's are disabled and
  5808. # if all the row plot's are enabled also enable the general plot checkbox
  5809. cb_cnt = 0
  5810. total_row = self.ui.cnc_tools_table.rowCount()
  5811. for row in range(total_row):
  5812. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  5813. cb_cnt += 1
  5814. else:
  5815. cb_cnt -= 1
  5816. if cb_cnt < total_row:
  5817. self.ui.plot_cb.setChecked(False)
  5818. else:
  5819. self.ui.plot_cb.setChecked(True)
  5820. self.ui_connect()
  5821. def plot(self, visible=None, kind='all'):
  5822. # Does all the required setup and returns False
  5823. # if the 'ptint' option is set to False.
  5824. if not FlatCAMObj.plot(self):
  5825. return
  5826. visible = visible if visible else self.options['plot']
  5827. if self.app.is_legacy is False:
  5828. if self.ui.annotation_cb.get_value() and self.ui.plot_cb.get_value():
  5829. self.text_col.enabled = True
  5830. else:
  5831. self.text_col.enabled = False
  5832. self.annotation.redraw()
  5833. try:
  5834. if self.multitool is False: # single tool usage
  5835. try:
  5836. dia_plot = float(self.options["tooldia"])
  5837. except ValueError:
  5838. # we may have a tuple with only one element and a comma
  5839. dia_plot = [float(el) for el in self.options["tooldia"].split(',') if el != ''][0]
  5840. self.plot2(dia_plot, obj=self, visible=visible, kind=kind)
  5841. else:
  5842. # multiple tools usage
  5843. if self.cnc_tools:
  5844. for tooluid_key in self.cnc_tools:
  5845. tooldia = float('%.*f' % (self.decimals, float(self.cnc_tools[tooluid_key]['tooldia'])))
  5846. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  5847. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  5848. # TODO: until the gcode parsed will be stored on each Excellon tool this will not get executed
  5849. if self.exc_cnc_tools:
  5850. for tooldia_key in self.exc_cnc_tools:
  5851. tooldia = float('%.*f' % (self.decimals, float(tooldia_key)))
  5852. # gcode_parsed = self.cnc_tools[tooldia_key]['gcode_parsed']
  5853. gcode_parsed = self.gcode_parsed
  5854. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  5855. self.shapes.redraw()
  5856. except (ObjectDeleted, AttributeError):
  5857. self.shapes.clear(update=True)
  5858. if self.app.is_legacy is False:
  5859. self.annotation.clear(update=True)
  5860. def on_annotation_change(self):
  5861. if self.app.is_legacy is False:
  5862. if self.ui.annotation_cb.get_value():
  5863. self.text_col.enabled = True
  5864. else:
  5865. self.text_col.enabled = False
  5866. # kind = self.ui.cncplot_method_combo.get_value()
  5867. # self.plot(kind=kind)
  5868. self.annotation.redraw()
  5869. else:
  5870. kind = self.ui.cncplot_method_combo.get_value()
  5871. self.plot(kind=kind)
  5872. def convert_units(self, units):
  5873. log.debug("FlatCAMObj.FlatCAMECNCjob.convert_units()")
  5874. factor = CNCjob.convert_units(self, units)
  5875. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  5876. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  5877. 'endz', 'toolchangez']
  5878. temp_tools_dict = {}
  5879. tool_dia_copy = {}
  5880. data_copy = {}
  5881. for tooluid_key, tooluid_value in self.cnc_tools.items():
  5882. for dia_key, dia_value in tooluid_value.items():
  5883. if dia_key == 'tooldia':
  5884. dia_value *= factor
  5885. dia_value = float('%.*f' % (self.decimals, dia_value))
  5886. tool_dia_copy[dia_key] = dia_value
  5887. if dia_key == 'offset':
  5888. tool_dia_copy[dia_key] = dia_value
  5889. if dia_key == 'offset_value':
  5890. dia_value *= factor
  5891. tool_dia_copy[dia_key] = dia_value
  5892. if dia_key == 'type':
  5893. tool_dia_copy[dia_key] = dia_value
  5894. if dia_key == 'tool_type':
  5895. tool_dia_copy[dia_key] = dia_value
  5896. if dia_key == 'data':
  5897. for data_key, data_value in dia_value.items():
  5898. # convert the form fields that are convertible
  5899. for param in param_list:
  5900. if data_key == param and data_value is not None:
  5901. data_copy[data_key] = data_value * factor
  5902. # copy the other dict entries that are not convertible
  5903. if data_key not in param_list:
  5904. data_copy[data_key] = data_value
  5905. tool_dia_copy[dia_key] = deepcopy(data_copy)
  5906. data_copy.clear()
  5907. if dia_key == 'gcode':
  5908. tool_dia_copy[dia_key] = dia_value
  5909. if dia_key == 'gcode_parsed':
  5910. tool_dia_copy[dia_key] = dia_value
  5911. if dia_key == 'solid_geometry':
  5912. tool_dia_copy[dia_key] = dia_value
  5913. # if dia_key == 'solid_geometry':
  5914. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  5915. # if dia_key == 'gcode_parsed':
  5916. # for g in dia_value:
  5917. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  5918. #
  5919. # tool_dia_copy['gcode_parsed'] = deepcopy(dia_value)
  5920. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  5921. temp_tools_dict.update({
  5922. tooluid_key: deepcopy(tool_dia_copy)
  5923. })
  5924. tool_dia_copy.clear()
  5925. self.cnc_tools.clear()
  5926. self.cnc_tools = deepcopy(temp_tools_dict)
  5927. class FlatCAMScript(FlatCAMObj):
  5928. """
  5929. Represents a TCL script object.
  5930. """
  5931. optionChanged = QtCore.pyqtSignal(str)
  5932. ui_type = ScriptObjectUI
  5933. def __init__(self, name):
  5934. self.decimals = self.app.decimals
  5935. FlatCAMApp.App.log.debug("Creating a FlatCAMScript object...")
  5936. FlatCAMObj.__init__(self, name)
  5937. self.kind = "script"
  5938. self.options.update({
  5939. "plot": True,
  5940. "type": 'Script',
  5941. "source_file": '',
  5942. })
  5943. self.units = ''
  5944. self.ser_attrs = ['options', 'kind', 'source_file']
  5945. self.source_file = ''
  5946. self.script_code = ''
  5947. self.units_found = self.app.defaults['units']
  5948. # self.script_editor_tab = TextEditor(app=self.app, plain_text=True)
  5949. self.script_editor_tab = TextEditor(app=self.app, plain_text=True)
  5950. def set_ui(self, ui):
  5951. FlatCAMObj.set_ui(self, ui)
  5952. FlatCAMApp.App.log.debug("FlatCAMScript.set_ui()")
  5953. assert isinstance(self.ui, ScriptObjectUI), \
  5954. "Expected a ScriptObjectUI, got %s" % type(self.ui)
  5955. self.units = self.app.defaults['units'].upper()
  5956. self.units_found = self.app.defaults['units']
  5957. # Fill form fields only on object create
  5958. self.to_form()
  5959. # Show/Hide Advanced Options
  5960. if self.app.defaults["global_app_level"] == 'b':
  5961. self.ui.level.setText(_(
  5962. '<span style="color:green;"><b>Basic</b></span>'
  5963. ))
  5964. else:
  5965. self.ui.level.setText(_(
  5966. '<span style="color:red;"><b>Advanced</b></span>'
  5967. ))
  5968. # tab_here = False
  5969. # # try to not add too many times a tab that it is already installed
  5970. # for idx in range(self.app.ui.plot_tab_area.count()):
  5971. # if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  5972. # tab_here = True
  5973. # break
  5974. #
  5975. # # add the tab if it is not already added
  5976. # if tab_here is False:
  5977. # self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  5978. # self.script_editor_tab.setObjectName(self.options['name'])
  5979. self.app.ui.plot_tab_area.addTab(self.script_editor_tab, '%s' % _("Script Editor"))
  5980. self.script_editor_tab.setObjectName(self.options['name'])
  5981. # first clear previous text in text editor (if any)
  5982. # self.script_editor_tab.code_editor.clear()
  5983. # self.script_editor_tab.code_editor.setReadOnly(False)
  5984. self.ui.autocomplete_cb.set_value(self.app.defaults['script_autocompleter'])
  5985. self.on_autocomplete_changed(state=self.app.defaults['script_autocompleter'])
  5986. self.script_editor_tab.buttonRun.show()
  5987. # Switch plot_area to CNCJob tab
  5988. self.app.ui.plot_tab_area.setCurrentWidget(self.script_editor_tab)
  5989. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5990. self.script_editor_tab.buttonOpen.clicked.disconnect()
  5991. self.script_editor_tab.buttonOpen.clicked.connect(lambda: self.script_editor_tab.handleOpen(filt=flt))
  5992. self.script_editor_tab.buttonSave.clicked.disconnect()
  5993. self.script_editor_tab.buttonSave.clicked.connect(lambda: self.script_editor_tab.handleSaveGCode(filt=flt))
  5994. self.script_editor_tab.buttonRun.clicked.connect(self.handle_run_code)
  5995. self.script_editor_tab.handleTextChanged()
  5996. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  5997. self.ser_attrs = ['options', 'kind', 'source_file']
  5998. # ---------------------------------------------------- #
  5999. # ----------- LOAD THE TEXT SOURCE FILE -------------- #
  6000. # ---------------------------------------------------- #
  6001. self.app.proc_container.view.set_busy(_("Loading..."))
  6002. self.script_editor_tab.t_frame.hide()
  6003. try:
  6004. self.script_editor_tab.code_editor.setPlainText(self.source_file)
  6005. # for line in self.source_file.splitlines():
  6006. # QtWidgets.QApplication.processEvents()
  6007. # self.script_editor_tab.code_editor.append(line)
  6008. except Exception as e:
  6009. log.debug("FlatCAMScript.set_ui() --> %s" % str(e))
  6010. self.script_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.End)
  6011. self.script_editor_tab.t_frame.show()
  6012. self.app.proc_container.view.set_idle()
  6013. self.build_ui()
  6014. def build_ui(self):
  6015. FlatCAMObj.build_ui(self)
  6016. def handle_run_code(self):
  6017. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  6018. # tries to print on a hidden widget, therefore show the dock if hidden
  6019. if self.app.ui.shell_dock.isHidden():
  6020. self.app.ui.shell_dock.show()
  6021. self.script_code = deepcopy(self.script_editor_tab.code_editor.toPlainText())
  6022. old_line = ''
  6023. for tcl_command_line in self.script_code.splitlines():
  6024. # do not process lines starting with '#' = comment and empty lines
  6025. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  6026. # id FlatCAM is run in Windows then replace all the slashes with
  6027. # the UNIX style slash that TCL understands
  6028. if sys.platform == 'win32':
  6029. if "open" in tcl_command_line:
  6030. tcl_command_line = tcl_command_line.replace('\\', '/')
  6031. if old_line != '':
  6032. new_command = old_line + tcl_command_line + '\n'
  6033. else:
  6034. new_command = tcl_command_line
  6035. # execute the actual Tcl command
  6036. try:
  6037. self.app.shell.open_proccessing() # Disables input box.
  6038. result = self.app.tcl.eval(str(new_command))
  6039. if result != 'None':
  6040. self.app.shell.append_output(result + '\n')
  6041. old_line = ''
  6042. except tk.TclError:
  6043. old_line = old_line + tcl_command_line + '\n'
  6044. except Exception as e:
  6045. log.debug("FlatCAMScript.handleRunCode() --> %s" % str(e))
  6046. if old_line != '':
  6047. # it means that the script finished with an error
  6048. result = self.app.tcl.eval("set errorInfo")
  6049. log.error("Exec command Exception: %s" % (result + '\n'))
  6050. self.app.shell.append_error('ERROR: ' + result + '\n')
  6051. self.app.shell.close_proccessing()
  6052. def on_autocomplete_changed(self, state):
  6053. if state:
  6054. self.script_editor_tab.code_editor.completer_enable = True
  6055. else:
  6056. self.script_editor_tab.code_editor.completer_enable = False
  6057. def to_dict(self):
  6058. """
  6059. Returns a representation of the object as a dictionary.
  6060. Attributes to include are listed in ``self.ser_attrs``.
  6061. :return: A dictionary-encoded copy of the object.
  6062. :rtype: dict
  6063. """
  6064. d = {}
  6065. for attr in self.ser_attrs:
  6066. d[attr] = getattr(self, attr)
  6067. return d
  6068. def from_dict(self, d):
  6069. """
  6070. Sets object's attributes from a dictionary.
  6071. Attributes to include are listed in ``self.ser_attrs``.
  6072. This method will look only for only and all the
  6073. attributes in ``self.ser_attrs``. They must all
  6074. be present. Use only for deserializing saved
  6075. objects.
  6076. :param d: Dictionary of attributes to set in the object.
  6077. :type d: dict
  6078. :return: None
  6079. """
  6080. for attr in self.ser_attrs:
  6081. setattr(self, attr, d[attr])
  6082. class FlatCAMDocument(FlatCAMObj):
  6083. """
  6084. Represents a Document object.
  6085. """
  6086. optionChanged = QtCore.pyqtSignal(str)
  6087. ui_type = DocumentObjectUI
  6088. def __init__(self, name):
  6089. self.decimals = self.app.decimals
  6090. FlatCAMApp.App.log.debug("Creating a Document object...")
  6091. FlatCAMObj.__init__(self, name)
  6092. self.kind = "document"
  6093. self.units = ''
  6094. self.ser_attrs = ['options', 'kind', 'source_file']
  6095. self.source_file = ''
  6096. self.doc_code = ''
  6097. self.font_italic = None
  6098. self.font_bold = None
  6099. self.font_underline =None
  6100. self.document_editor_tab = None
  6101. self._read_only = False
  6102. self.units_found = self.app.defaults['units']
  6103. def set_ui(self, ui):
  6104. FlatCAMObj.set_ui(self, ui)
  6105. FlatCAMApp.App.log.debug("FlatCAMDocument.set_ui()")
  6106. assert isinstance(self.ui, DocumentObjectUI), \
  6107. "Expected a DocumentObjectUI, got %s" % type(self.ui)
  6108. self.units = self.app.defaults['units'].upper()
  6109. self.units_found = self.app.defaults['units']
  6110. # Fill form fields only on object create
  6111. self.to_form()
  6112. # Show/Hide Advanced Options
  6113. if self.app.defaults["global_app_level"] == 'b':
  6114. self.ui.level.setText(_(
  6115. '<span style="color:green;"><b>Basic</b></span>'
  6116. ))
  6117. else:
  6118. self.ui.level.setText(_(
  6119. '<span style="color:red;"><b>Advanced</b></span>'
  6120. ))
  6121. self.document_editor_tab = TextEditor(app=self.app)
  6122. stylesheet = """
  6123. QTextEdit {selection-background-color:%s;
  6124. selection-color:white;
  6125. }
  6126. """ % self.app.defaults["document_sel_color"]
  6127. self.document_editor_tab.code_editor.setStyleSheet(stylesheet)
  6128. # first clear previous text in text editor (if any)
  6129. self.document_editor_tab.code_editor.clear()
  6130. self.document_editor_tab.code_editor.setReadOnly(self._read_only)
  6131. self.document_editor_tab.buttonRun.hide()
  6132. self.ui.autocomplete_cb.set_value(self.app.defaults['document_autocompleter'])
  6133. self.on_autocomplete_changed(state=self.app.defaults['document_autocompleter'])
  6134. self.on_tab_size_change(val=self.app.defaults['document_tab_size'])
  6135. flt = "FlatCAM Docs (*.FlatDoc);;All Files (*.*)"
  6136. # ######################################################################
  6137. # ######################## SIGNALS #####################################
  6138. # ######################################################################
  6139. self.document_editor_tab.buttonOpen.clicked.disconnect()
  6140. self.document_editor_tab.buttonOpen.clicked.connect(lambda: self.document_editor_tab.handleOpen(filt=flt))
  6141. self.document_editor_tab.buttonSave.clicked.disconnect()
  6142. self.document_editor_tab.buttonSave.clicked.connect(lambda: self.document_editor_tab.handleSaveGCode(filt=flt))
  6143. self.document_editor_tab.code_editor.textChanged.connect(self.on_text_changed)
  6144. self.ui.font_type_cb.currentFontChanged.connect(self.font_family)
  6145. self.ui.font_size_cb.activated.connect(self.font_size)
  6146. self.ui.font_bold_tb.clicked.connect(self.on_bold_button)
  6147. self.ui.font_italic_tb.clicked.connect(self.on_italic_button)
  6148. self.ui.font_under_tb.clicked.connect(self.on_underline_button)
  6149. self.ui.font_color_entry.editingFinished.connect(self.on_font_color_entry)
  6150. self.ui.font_color_button.clicked.connect(self.on_font_color_button)
  6151. self.ui.sel_color_entry.editingFinished.connect(self.on_selection_color_entry)
  6152. self.ui.sel_color_button.clicked.connect(self.on_selection_color_button)
  6153. self.ui.al_left_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignLeft))
  6154. self.ui.al_center_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignCenter))
  6155. self.ui.al_right_tb.clicked.connect(lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignRight))
  6156. self.ui.al_justify_tb.clicked.connect(
  6157. lambda: self.document_editor_tab.code_editor.setAlignment(Qt.AlignJustify)
  6158. )
  6159. self.ui.autocomplete_cb.stateChanged.connect(self.on_autocomplete_changed)
  6160. self.ui.tab_size_spinner.returnPressed.connect(self.on_tab_size_change)
  6161. # #######################################################################
  6162. self.ui.font_color_entry.set_value(self.app.defaults['document_font_color'])
  6163. self.ui.font_color_button.setStyleSheet(
  6164. "background-color:%s" % str(self.app.defaults['document_font_color']))
  6165. self.ui.sel_color_entry.set_value(self.app.defaults['document_sel_color'])
  6166. self.ui.sel_color_button.setStyleSheet(
  6167. "background-color:%s" % self.app.defaults['document_sel_color'])
  6168. self.ui.font_size_cb.setCurrentIndex(int(self.app.defaults['document_font_size']))
  6169. self.document_editor_tab.handleTextChanged()
  6170. self.ser_attrs = ['options', 'kind', 'source_file']
  6171. if Qt.mightBeRichText(self.source_file):
  6172. self.document_editor_tab.code_editor.setHtml(self.source_file)
  6173. else:
  6174. for line in self.source_file.splitlines():
  6175. self.document_editor_tab.code_editor.append(line)
  6176. self.build_ui()
  6177. @property
  6178. def read_only(self):
  6179. return self._read_only
  6180. @read_only.setter
  6181. def read_only(self, val):
  6182. if val:
  6183. self._read_only = True
  6184. else:
  6185. self._read_only = False
  6186. def build_ui(self):
  6187. FlatCAMObj.build_ui(self)
  6188. tab_here = False
  6189. # try to not add too many times a tab that it is already installed
  6190. for idx in range(self.app.ui.plot_tab_area.count()):
  6191. if self.app.ui.plot_tab_area.widget(idx).objectName() == self.options['name']:
  6192. tab_here = True
  6193. break
  6194. # add the tab if it is not already added
  6195. if tab_here is False:
  6196. self.app.ui.plot_tab_area.addTab(self.document_editor_tab, '%s' % _("Document Editor"))
  6197. self.document_editor_tab.setObjectName(self.options['name'])
  6198. # Switch plot_area to CNCJob tab
  6199. self.app.ui.plot_tab_area.setCurrentWidget(self.document_editor_tab)
  6200. def on_autocomplete_changed(self, state):
  6201. if state:
  6202. self.document_editor_tab.code_editor.completer_enable = True
  6203. else:
  6204. self.document_editor_tab.code_editor.completer_enable = False
  6205. def on_tab_size_change(self, val=None):
  6206. try:
  6207. self.ui.tab_size_spinner.returnPressed.disconnect(self.on_tab_size_change)
  6208. except TypeError:
  6209. pass
  6210. if val:
  6211. self.ui.tab_size_spinner.set_value(val)
  6212. tab_balue = int(self.ui.tab_size_spinner.get_value())
  6213. self.document_editor_tab.code_editor.setTabStopWidth(tab_balue)
  6214. self.app.defaults['document_tab_size'] = tab_balue
  6215. self.ui.tab_size_spinner.returnPressed.connect(self.on_tab_size_change)
  6216. def on_text_changed(self):
  6217. self.source_file = self.document_editor_tab.code_editor.toHtml()
  6218. # print(self.source_file)
  6219. def font_family(self, font):
  6220. # self.document_editor_tab.code_editor.selectAll()
  6221. font.setPointSize(float(self.ui.font_size_cb.get_value()))
  6222. self.document_editor_tab.code_editor.setCurrentFont(font)
  6223. self.font_name = self.ui.font_type_cb.currentFont().family()
  6224. def font_size(self):
  6225. # self.document_editor_tab.code_editor.selectAll()
  6226. self.document_editor_tab.code_editor.setFontPointSize(float(self.ui.font_size_cb.get_value()))
  6227. def on_bold_button(self):
  6228. if self.ui.font_bold_tb.isChecked():
  6229. self.document_editor_tab.code_editor.setFontWeight(QtGui.QFont.Bold)
  6230. self.font_bold = True
  6231. else:
  6232. self.document_editor_tab.code_editor.setFontWeight(QtGui.QFont.Normal)
  6233. self.font_bold = False
  6234. def on_italic_button(self):
  6235. if self.ui.font_italic_tb.isChecked():
  6236. self.document_editor_tab.code_editor.setFontItalic(True)
  6237. self.font_italic = True
  6238. else:
  6239. self.document_editor_tab.code_editor.setFontItalic(False)
  6240. self.font_italic = False
  6241. def on_underline_button(self):
  6242. if self.ui.font_under_tb.isChecked():
  6243. self.document_editor_tab.code_editor.setFontUnderline(True)
  6244. self.font_underline = True
  6245. else:
  6246. self.document_editor_tab.code_editor.setFontUnderline(False)
  6247. self.font_underline = False
  6248. # Setting font colors handlers
  6249. def on_font_color_entry(self):
  6250. self.app.defaults['document_font_color'] = self.ui.font_color_entry.get_value()
  6251. self.ui.font_color_button.setStyleSheet("background-color:%s" % str(self.app.defaults['document_font_color']))
  6252. def on_font_color_button(self):
  6253. current_color = QtGui.QColor(self.app.defaults['document_font_color'])
  6254. c_dialog = QtWidgets.QColorDialog()
  6255. font_color = c_dialog.getColor(initial=current_color)
  6256. if font_color.isValid() is False:
  6257. return
  6258. self.document_editor_tab.code_editor.setTextColor(font_color)
  6259. self.ui.font_color_button.setStyleSheet("background-color:%s" % str(font_color.name()))
  6260. new_val = str(font_color.name())
  6261. self.ui.font_color_entry.set_value(new_val)
  6262. self.app.defaults['document_font_color'] = new_val
  6263. # Setting selection colors handlers
  6264. def on_selection_color_entry(self):
  6265. self.app.defaults['document_sel_color'] = self.ui.sel_color_entry.get_value()
  6266. self.ui.sel_color_button.setStyleSheet("background-color:%s" % str(self.app.defaults['document_sel_color']))
  6267. def on_selection_color_button(self):
  6268. current_color = QtGui.QColor(self.app.defaults['document_sel_color'])
  6269. c_dialog = QtWidgets.QColorDialog()
  6270. sel_color = c_dialog.getColor(initial=current_color)
  6271. if sel_color.isValid() is False:
  6272. return
  6273. p = QtGui.QPalette()
  6274. p.setColor(QtGui.QPalette.Highlight, sel_color)
  6275. p.setColor(QtGui.QPalette.HighlightedText, QtGui.QColor('white'))
  6276. self.document_editor_tab.code_editor.setPalette(p)
  6277. self.ui.sel_color_button.setStyleSheet("background-color:%s" % str(sel_color.name()))
  6278. new_val = str(sel_color.name())
  6279. self.ui.sel_color_entry.set_value(new_val)
  6280. self.app.defaults['document_sel_color'] = new_val
  6281. def to_dict(self):
  6282. """
  6283. Returns a representation of the object as a dictionary.
  6284. Attributes to include are listed in ``self.ser_attrs``.
  6285. :return: A dictionary-encoded copy of the object.
  6286. :rtype: dict
  6287. """
  6288. d = {}
  6289. for attr in self.ser_attrs:
  6290. d[attr] = getattr(self, attr)
  6291. return d
  6292. def from_dict(self, d):
  6293. """
  6294. Sets object's attributes from a dictionary.
  6295. Attributes to include are listed in ``self.ser_attrs``.
  6296. This method will look only for only and all the
  6297. attributes in ``self.ser_attrs``. They must all
  6298. be present. Use only for deserializing saved
  6299. objects.
  6300. :param d: Dictionary of attributes to set in the object.
  6301. :type d: dict
  6302. :return: None
  6303. """
  6304. for attr in self.ser_attrs:
  6305. setattr(self, attr, d[attr])
  6306. # end of file