FlatCAMObj.py 258 KB

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