FlatCAMObj.py 260 KB

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