FlatCAMObj.py 236 KB

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