FlatCAMObj.py 254 KB

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