FlatCAMObj.py 246 KB

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