FlatCAMObj.py 300 KB

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