FlatCAMObj.py 234 KB

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