FlatCAMApp.py 414 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import tkinter as tk
  20. from PyQt5 import QtPrintSupport
  21. from contextlib import contextmanager
  22. import gc
  23. from xml.dom.minidom import parseString as parse_xml_string
  24. # #######################################
  25. # # Imports part of FlatCAM ##
  26. # #######################################
  27. from ObjectCollection import *
  28. from FlatCAMObj import *
  29. from flatcamGUI.PlotCanvas import *
  30. from flatcamGUI.FlatCAMGUI import *
  31. from FlatCAMCommon import LoudDict
  32. from FlatCAMPostProc import load_postprocessors
  33. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  34. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  35. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  36. from FlatCAMProcess import *
  37. from FlatCAMWorkerStack import WorkerStack
  38. from flatcamGUI.VisPyVisuals import Color
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. from flatcamTools import *
  42. from multiprocessing import Pool
  43. import tclCommands
  44. import gettext
  45. import FlatCAMTranslation as fcTranslate
  46. import builtins
  47. fcTranslate.apply_language('strings')
  48. if '_' not in builtins.__dict__:
  49. _ = gettext.gettext
  50. # ########################################
  51. # # App ###
  52. # ########################################
  53. class App(QtCore.QObject):
  54. """
  55. The main application class. The constructor starts the GUI.
  56. """
  57. # Get Cmd Line Options
  58. cmd_line_shellfile = ''
  59. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  60. try:
  61. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  62. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  63. except getopt.GetoptError:
  64. print(cmd_line_help)
  65. sys.exit(2)
  66. for opt, arg in cmd_line_options:
  67. if opt == '-h':
  68. print(cmd_line_help)
  69. sys.exit()
  70. elif opt == '--shellfile':
  71. cmd_line_shellfile = arg
  72. # ## Logging ###
  73. log = logging.getLogger('base')
  74. log.setLevel(logging.DEBUG)
  75. # log.setLevel(logging.WARNING)
  76. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  77. handler = logging.StreamHandler()
  78. handler.setFormatter(formatter)
  79. log.addHandler(handler)
  80. # ####################################
  81. # Version and VERSION DATE ###########
  82. # ####################################
  83. version = 8.96
  84. version_date = "2019/08/31"
  85. beta = True
  86. # current date now
  87. date = str(datetime.today()).rpartition('.')[0]
  88. date = ''.join(c for c in date if c not in ':-')
  89. date = date.replace(' ', '_')
  90. # URL for update checks and statistics
  91. version_url = "http://flatcam.org/version"
  92. # App URL
  93. app_url = "http://flatcam.org"
  94. # Manual URL
  95. manual_url = "http://flatcam.org/manual/index.html"
  96. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  97. # this variable will hold the project status
  98. # if True it will mean that the project was modified and not saved
  99. should_we_save = False
  100. # flag is True if saving action has been triggered
  101. save_in_progress = False
  102. # #################
  103. # # Signals ##
  104. # #################
  105. # Inform the user
  106. # Handled by:
  107. # * App.info() --> Print on the status bar
  108. inform = QtCore.pyqtSignal(str)
  109. app_quit = QtCore.pyqtSignal()
  110. # General purpose background task
  111. worker_task = QtCore.pyqtSignal(dict)
  112. # File opened
  113. # Handled by:
  114. # * register_folder()
  115. # * register_recent()
  116. # Note: Setting the parameters to unicode does not seem
  117. # to have an effect. Then are received as Qstring
  118. # anyway.
  119. # File type and filename
  120. file_opened = QtCore.pyqtSignal(str, str)
  121. # File type and filename
  122. file_saved = QtCore.pyqtSignal(str, str)
  123. # Percentage of progress
  124. progress = QtCore.pyqtSignal(int)
  125. plots_updated = QtCore.pyqtSignal()
  126. # Emitted by new_object() and passes the new object as argument, plot flag.
  127. # on_object_created() adds the object to the collection, plots on appropriate flag
  128. # and emits new_object_available.
  129. object_created = QtCore.pyqtSignal(object, bool, bool)
  130. # Emitted when a object has been changed (like scaled, mirrored)
  131. object_changed = QtCore.pyqtSignal(object)
  132. # Emitted after object has been plotted.
  133. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  134. object_plotted = QtCore.pyqtSignal(object)
  135. # Emitted when a new object has been added or deleted from/to the collection
  136. object_status_changed = QtCore.pyqtSignal(object, str)
  137. message = QtCore.pyqtSignal(str, str, str)
  138. # Emmited when shell command is finished(one command only)
  139. shell_command_finished = QtCore.pyqtSignal(object)
  140. # Emitted when multiprocess pool has been recreated
  141. pool_recreated = QtCore.pyqtSignal(object)
  142. # Emitted when an unhandled exception happens
  143. # in the worker task.
  144. thread_exception = QtCore.pyqtSignal(object)
  145. # used to signal that there are arguments for the app
  146. args_at_startup = QtCore.pyqtSignal()
  147. def __init__(self, user_defaults=True, post_gui=None):
  148. """
  149. Starts the application.
  150. :return: app
  151. :rtype: App
  152. """
  153. App.log.info("FlatCAM Starting...")
  154. self.main_thread = QtWidgets.QApplication.instance().thread()
  155. # #######################
  156. # # ## OS-specific ######
  157. # #######################
  158. portable = False
  159. # Folder for user settings.
  160. if sys.platform == 'win32':
  161. from win32com.shell import shell, shellcon
  162. if platform.architecture()[0] == '32bit':
  163. App.log.debug("Win32!")
  164. else:
  165. App.log.debug("Win64!")
  166. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  167. try:
  168. with open(config_file, 'r') as f:
  169. try:
  170. for line in f:
  171. param = str(line).rpartition('=')
  172. if param[0] == 'portable':
  173. try:
  174. portable = eval(param[2])
  175. except NameError:
  176. portable = False
  177. except Exception as e:
  178. log.debug('App.__init__() -->%s' % str(e))
  179. return
  180. except FileNotFoundError:
  181. pass
  182. if portable is False:
  183. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  184. else:
  185. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  186. self.os = 'windows'
  187. else: # Linux/Unix/MacOS
  188. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  189. self.os = 'unix'
  190. # ############################ ##
  191. # # ## Setup folders and files # ##
  192. # ############################ ##
  193. if not os.path.exists(self.data_path):
  194. os.makedirs(self.data_path)
  195. App.log.debug('Created data folder: ' + self.data_path)
  196. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  197. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  198. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  199. if not os.path.exists(self.postprocessorpaths):
  200. os.makedirs(self.postprocessorpaths)
  201. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  202. # create current_defaults.FlatConfig file if there is none
  203. try:
  204. f = open(self.data_path + '/current_defaults.FlatConfig')
  205. f.close()
  206. except IOError:
  207. App.log.debug('Creating empty current_defaults.FlatConfig')
  208. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  209. json.dump({}, f)
  210. f.close()
  211. # create factory_defaults.FlatConfig file if there is none
  212. try:
  213. f = open(self.data_path + '/factory_defaults.FlatConfig')
  214. f.close()
  215. except IOError:
  216. App.log.debug('Creating empty factory_defaults.FlatConfig')
  217. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  218. json.dump({}, f)
  219. f.close()
  220. try:
  221. f = open(self.data_path + '/recent.json')
  222. f.close()
  223. except IOError:
  224. App.log.debug('Creating empty recent.json')
  225. f = open(self.data_path + '/recent.json', 'w')
  226. json.dump([], f)
  227. f.close()
  228. try:
  229. fp = open(self.data_path + '/recent_projects.json')
  230. fp.close()
  231. except IOError:
  232. App.log.debug('Creating empty recent_projects.json')
  233. fp = open(self.data_path + '/recent_projects.json', 'w')
  234. json.dump([], fp)
  235. fp.close()
  236. # Application directory. CHDIR to it. Otherwise, trying to load
  237. # GUI icons will fail as their path is relative.
  238. # This will fail under cx_freeze ...
  239. self.app_home = os.path.dirname(os.path.realpath(__file__))
  240. App.log.debug("Application path is " + self.app_home)
  241. App.log.debug("Started in " + os.getcwd())
  242. # cx_freeze workaround
  243. if os.path.isfile(self.app_home):
  244. self.app_home = os.path.dirname(self.app_home)
  245. os.chdir(self.app_home)
  246. # Create multiprocessing pool
  247. self.pool = Pool()
  248. # variable to store mouse coordinates
  249. self.mouse = [0, 0]
  250. # ###################
  251. # # Initialize GUI ##
  252. # ###################
  253. # FlatCAM colors used in plotting
  254. self.FC_light_green = '#BBF268BF'
  255. self.FC_dark_green = '#006E20BF'
  256. self.FC_light_blue = '#a5a5ffbf'
  257. self.FC_dark_blue = '#0000ffbf'
  258. QtCore.QObject.__init__(self)
  259. self.ui = FlatCAMGUI(self.version, self.beta, self)
  260. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  261. self.ui.final_save.connect(self.final_save)
  262. # #############
  263. # ### Data ####
  264. # #############
  265. self.recent = []
  266. self.recent_projects = []
  267. self.clipboard = QtWidgets.QApplication.clipboard()
  268. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  269. self.project_filename = None
  270. self.toggle_units_ignore = False
  271. # self.defaults_form = PreferencesUI()
  272. # when adding entries here read the comments in the method found bellow named:
  273. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  274. self.defaults_form_fields = {
  275. # General App
  276. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  277. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  278. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  279. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  280. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  281. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  282. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  283. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  284. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  285. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  286. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  287. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  288. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  289. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  290. "global_delete_confirmation": self.ui.general_defaults_form.general_app_group.delete_conf_cb,
  291. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  292. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  293. # General GUI Preferences
  294. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  295. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  296. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  297. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  298. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  299. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  300. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  301. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  302. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  303. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  304. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  305. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  306. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  307. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  308. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  309. # General GUI Settings
  310. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  311. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  312. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  313. # Gerber General
  314. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  315. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  316. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  317. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  318. # Gerber Options
  319. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  320. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  321. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  322. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  323. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  324. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  325. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  326. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  327. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  328. # Gerber Advanced Options
  329. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  330. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  331. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  332. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  333. # Gerber Export
  334. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  335. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  336. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  337. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  338. # Gerber Editor
  339. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  340. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  341. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  342. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  343. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  344. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  345. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  346. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  347. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  348. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  349. "gerber_editor_circ_angle":
  350. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  351. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  352. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  353. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  354. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  355. # Excellon General
  356. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  357. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  358. "excellon_format_upper_in":
  359. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  360. "excellon_format_lower_in":
  361. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  362. "excellon_format_upper_mm":
  363. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  364. "excellon_format_lower_mm":
  365. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  366. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  367. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  368. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  369. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  370. # Excellon Options
  371. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  372. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  373. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  374. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  375. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  376. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  377. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  378. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  379. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  380. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  381. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  382. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  383. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  384. # Excellon Advanced Options
  385. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  386. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  387. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  388. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  389. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  390. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  391. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  392. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  393. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  394. # Excellon Export
  395. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  396. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  397. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  398. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  399. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  400. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  401. # Excellon Editor
  402. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  403. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  404. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  405. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  406. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  407. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  408. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  409. "excellon_editor_circ_angle":
  410. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  411. # Excellon Slots
  412. "excellon_editor_slot_direction":
  413. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  414. "excellon_editor_slot_angle":
  415. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  416. "excellon_editor_slot_length":
  417. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  418. # Excellon Slots
  419. "excellon_editor_slot_array_size":
  420. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  421. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  422. "excellon_editor_slot_lin_pitch":
  423. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  424. "excellon_editor_slot_lin_angle":
  425. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  426. "excellon_editor_slot_circ_dir":
  427. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  428. "excellon_editor_slot_circ_angle":
  429. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  430. # Geometry General
  431. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  432. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  433. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  434. # Geometry Options
  435. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  436. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  437. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  438. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  439. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  440. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  441. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  442. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  443. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  444. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  445. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  446. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  447. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  448. # Geometry Advanced Options
  449. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  450. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  451. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  452. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  453. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  454. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  455. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  456. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  457. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  458. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  459. # Geometry Editor
  460. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  461. # CNCJob General
  462. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  463. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  464. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  465. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  466. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  467. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  468. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  469. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  470. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  471. # CNC Job Options
  472. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  473. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  474. # CNC Job Advanced Options
  475. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  476. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  477. # NCC Tool
  478. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  479. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  480. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  481. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  482. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  483. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  484. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  485. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  486. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  487. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  488. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  489. # CutOut Tool
  490. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  491. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  492. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  493. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  494. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  495. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  496. # Paint Area Tool
  497. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  498. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  499. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  500. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  501. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  502. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  503. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  504. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  505. # 2-sided Tool
  506. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  507. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  508. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  509. # Film Tool
  510. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  511. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  512. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  513. # Panelize Tool
  514. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  515. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  516. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  517. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  518. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  519. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  520. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  521. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  522. # Calculators Tool
  523. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  524. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  525. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  526. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  527. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  528. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  529. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  530. # Transformations Tool
  531. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  532. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  533. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  534. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  535. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  536. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  537. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  538. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  539. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  540. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  541. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  542. # SolderPaste Dispensing Tool
  543. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  544. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  545. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  546. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  547. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  548. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  549. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  550. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  551. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  552. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  553. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  554. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  555. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  556. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  557. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  558. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  559. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb
  560. }
  561. # ############################
  562. # ### LOAD POSTPROCESSORS ####
  563. # ############################
  564. self.postprocessors = load_postprocessors(self)
  565. for name in list(self.postprocessors.keys()):
  566. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  567. if name.partition('_')[0] == 'Paste':
  568. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  569. continue
  570. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  571. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  572. if name == 'hpgl':
  573. continue
  574. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  575. # ############################
  576. # ### LOAD LANGUAGES ####
  577. # ############################
  578. self.languages = fcTranslate.load_languages()
  579. for name in sorted(self.languages.values()):
  580. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  581. self.defaults = LoudDict()
  582. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  583. self.defaults.update({
  584. # Global APP Preferences
  585. "global_serial": 0,
  586. "global_stats": {},
  587. "global_tabs_detachable": True,
  588. "units": "IN",
  589. "global_app_level": 'b',
  590. "global_language": 'English',
  591. "global_version_check": True,
  592. "global_send_stats": True,
  593. "global_pan_button": '2',
  594. "global_mselect_key": 'Control',
  595. "global_project_at_startup": False,
  596. "global_project_autohide": True,
  597. "global_toggle_tooltips": True,
  598. "global_worker_number": 2,
  599. "global_tolerance": 0.01,
  600. "global_open_style": True,
  601. "global_delete_confirmation": True,
  602. "global_compression_level": 3,
  603. "global_save_compressed": True,
  604. # Global GUI Preferences
  605. "global_gridx": 0.0393701,
  606. "global_gridy": 0.0393701,
  607. "global_snap_max": 0.001968504,
  608. "global_workspace": False,
  609. "global_workspaceT": "A4P",
  610. "global_grid_context_menu": {
  611. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  612. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  613. },
  614. "global_plot_fill": '#BBF268BF',
  615. "global_plot_line": '#006E20BF',
  616. "global_sel_fill": '#a5a5ffbf',
  617. "global_sel_line": '#0000ffbf',
  618. "global_alt_sel_fill": '#BBF268BF',
  619. "global_alt_sel_line": '#006E20BF',
  620. "global_draw_color": '#FF0000',
  621. "global_sel_draw_color": '#0000FF',
  622. "global_proj_item_color": '#000000',
  623. "global_proj_item_dis_color": '#b7b7cb',
  624. "global_toolbar_view": 511,
  625. "global_background_timeout": 300000, # Default value is 5 minutes
  626. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  627. # (python trace only for unknown errors),
  628. # 1 = show trace(show trace always),
  629. # 2 = (For the future).
  630. # Persistence
  631. "global_last_folder": None,
  632. "global_last_save_folder": None,
  633. # Default window geometry
  634. "global_def_win_x": 100,
  635. "global_def_win_y": 100,
  636. "global_def_win_w": 1024,
  637. "global_def_win_h": 650,
  638. "global_def_notebook_width": 1,
  639. # Constants...
  640. "global_defaults_save_period_ms": 20000, # Time between default saves.
  641. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  642. "global_shell_at_startup": False, # Show the shell at startup.
  643. "global_recent_limit": 10, # Max. items in recent list.
  644. "fit_key": 'V',
  645. "zoom_out_key": '-',
  646. "zoom_in_key": '=',
  647. "grid_toggle_key": 'G',
  648. "global_zoom_ratio": 1.5,
  649. "global_point_clipboard_format": "(%.4f, %.4f)",
  650. "global_zdownrate": None,
  651. # General GUI Settings
  652. "global_hover": False,
  653. "global_selection_shape": True,
  654. "global_layout": "compact",
  655. # Gerber General
  656. "gerber_plot": True,
  657. "gerber_solid": True,
  658. "gerber_multicolored": False,
  659. "gerber_isotooldia": 0.00787402,
  660. "gerber_isopasses": 1,
  661. "gerber_isooverlap": 0.00393701,
  662. # Gerber Options
  663. "gerber_combine_passes": False,
  664. "gerber_milling_type": "cl",
  665. "gerber_noncoppermargin": 0.00393701,
  666. "gerber_noncopperrounded": False,
  667. "gerber_bboxmargin": 0.00393701,
  668. "gerber_bboxrounded": False,
  669. "gerber_circle_steps": 128,
  670. "gerber_use_buffer_for_union": True,
  671. # Gerber Advanced Options
  672. "gerber_aperture_display": False,
  673. "gerber_aperture_scale_factor": 1.0,
  674. "gerber_aperture_buffer_factor": 0.0,
  675. "gerber_follow": False,
  676. # Gerber Export
  677. "gerber_exp_units": 'IN',
  678. "gerber_exp_integer": 2,
  679. "gerber_exp_decimals": 4,
  680. "gerber_exp_zeros": 'L',
  681. # Gerber Editor
  682. "gerber_editor_sel_limit": 30,
  683. "gerber_editor_newcode": 10,
  684. "gerber_editor_newsize": 0.8,
  685. "gerber_editor_newtype": 'C',
  686. "gerber_editor_newdim": "0.5, 0.5",
  687. "gerber_editor_array_size": 5,
  688. "gerber_editor_lin_axis": 'X',
  689. "gerber_editor_lin_pitch": 1,
  690. "gerber_editor_lin_angle": 0.0,
  691. "gerber_editor_circ_dir": 'CW',
  692. "gerber_editor_circ_angle": 0.0,
  693. "gerber_editor_scale_f": 1.0,
  694. "gerber_editor_buff_f": 0.1,
  695. "gerber_editor_ma_low": 0.0,
  696. "gerber_editor_ma_high": 1.0,
  697. # Excellon General
  698. "excellon_plot": True,
  699. "excellon_solid": True,
  700. "excellon_format_upper_in": 2,
  701. "excellon_format_lower_in": 4,
  702. "excellon_format_upper_mm": 3,
  703. "excellon_format_lower_mm": 3,
  704. "excellon_zeros": "L",
  705. "excellon_units": "INCH",
  706. "excellon_optimization_type": 'B',
  707. "excellon_search_time": 3,
  708. # Excellon Options
  709. "excellon_drillz": -0.0590551,
  710. "excellon_travelz": 0.0787402,
  711. "excellon_feedrate": 3.14961,
  712. "excellon_spindlespeed": None,
  713. "excellon_spindledir": 'CW',
  714. "excellon_dwell": False,
  715. "excellon_dwelltime": 1,
  716. "excellon_toolchange": False,
  717. "excellon_toolchangez": 0.5,
  718. "excellon_ppname_e": 'default',
  719. "excellon_tooldia": 0.0314961,
  720. "excellon_slot_tooldia": 0.0708661,
  721. "excellon_gcode_type": "drills",
  722. # Excellon Advanced Options
  723. "excellon_offset": 0.0,
  724. "excellon_toolchangexy": "0.0, 0.0",
  725. "excellon_startz": None,
  726. "excellon_endz": 0.5,
  727. "excellon_feedrate_rapid": 31.4961,
  728. "excellon_z_pdepth": -0.02,
  729. "excellon_feedrate_probe": 3.14961,
  730. "excellon_f_plunge": False,
  731. "excellon_f_retract": False,
  732. # Excellon Export
  733. "excellon_exp_units": 'INCH',
  734. "excellon_exp_format": 'ndec',
  735. "excellon_exp_integer": 2,
  736. "excellon_exp_decimals": 4,
  737. "excellon_exp_zeros": 'LZ',
  738. "excellon_exp_slot_type": 'routing',
  739. # Excellon Editor
  740. "excellon_editor_sel_limit": 30,
  741. "excellon_editor_newdia": 0.039,
  742. "excellon_editor_array_size": 5,
  743. "excellon_editor_lin_dir": 'X',
  744. "excellon_editor_lin_pitch": 0.1,
  745. "excellon_editor_lin_angle": 0.0,
  746. "excellon_editor_circ_dir": 'CW',
  747. "excellon_editor_circ_angle": 12,
  748. # Excellon Slots
  749. "excellon_editor_slot_direction": 'X',
  750. "excellon_editor_slot_angle": 0.0,
  751. "excellon_editor_slot_length": 5.0,
  752. # Excellon Slot Array
  753. "excellon_editor_slot_array_size": 5,
  754. "excellon_editor_slot_lin_dir": 'X',
  755. "excellon_editor_slot_lin_pitch": 0.1,
  756. "excellon_editor_slot_lin_angle": 0.0,
  757. "excellon_editor_slot_circ_dir": 'CW',
  758. "excellon_editor_slot_circ_angle": 0.0,
  759. # Geometry General
  760. "geometry_plot": True,
  761. "geometry_circle_steps": 128,
  762. "geometry_cnctooldia": "0.0944882",
  763. # Geometry Options
  764. "geometry_cutz": -0.0944882,
  765. "geometry_vtipdia": 0.1,
  766. "geometry_vtipangle": 30,
  767. "geometry_multidepth": False,
  768. "geometry_depthperpass": 0.0314961,
  769. "geometry_travelz": 0.0787402,
  770. "geometry_toolchange": False,
  771. "geometry_toolchangez": 0.5,
  772. "geometry_feedrate": 3.14961,
  773. "geometry_feedrate_z": 3.14961,
  774. "geometry_spindlespeed": None,
  775. "geometry_spindledir": 'CW',
  776. "geometry_dwell": False,
  777. "geometry_dwelltime": 1,
  778. "geometry_ppname_g": 'default',
  779. # Geometry Advanced Options
  780. "geometry_toolchangexy": "0.0, 0.0",
  781. "geometry_startz": None,
  782. "geometry_endz": 0.5,
  783. "geometry_feedrate_rapid": 3.14961,
  784. "geometry_extracut": False,
  785. "geometry_z_pdepth": -0.02,
  786. "geometry_f_plunge": False,
  787. "geometry_feedrate_probe": 3.14961,
  788. "geometry_segx": 0.0,
  789. "geometry_segy": 0.0,
  790. # Geometry Editor
  791. "geometry_editor_sel_limit": 30,
  792. # CNC Job General
  793. "cncjob_plot": True,
  794. "cncjob_plot_kind": 'all',
  795. "cncjob_annotation": True,
  796. "cncjob_annotation_fontsize": 9,
  797. "cncjob_annotation_fontcolor": '#990000',
  798. "cncjob_tooldia": 0.0393701,
  799. "cncjob_coords_decimals": 4,
  800. "cncjob_fr_decimals": 2,
  801. "cncjob_steps_per_circle": 128,
  802. # CNC Job Options
  803. "cncjob_prepend": "",
  804. "cncjob_append": "",
  805. # CNC Job Advanced Options
  806. "cncjob_toolchange_macro": "",
  807. "cncjob_toolchange_macro_enable": False,
  808. "tools_ncctools": "0.0393701, 0.019685",
  809. "tools_nccorder": 'rev',
  810. "tools_nccoverlap": 0.015748,
  811. "tools_nccmargin": 0.0393701,
  812. "tools_nccmethod": "seed",
  813. "tools_nccconnect": True,
  814. "tools_ncccontour": True,
  815. "tools_nccrest": False,
  816. "tools_ncc_offset_choice": False,
  817. "tools_ncc_offset_value": 0.0000,
  818. "tools_nccref": 'itself',
  819. "tools_cutouttooldia": 0.0944882,
  820. "tools_cutoutkind": "single",
  821. "tools_cutoutmargin": 0.00393701,
  822. "tools_cutoutgapsize": 0.15748,
  823. "tools_gaps_ff": "4",
  824. "tools_cutout_convexshape": False,
  825. "tools_painttooldia": 0.023622,
  826. "tools_paintorder": 'rev',
  827. "tools_paintoverlap": 0.015748,
  828. "tools_paintmargin": 0.0,
  829. "tools_paintmethod": "seed",
  830. "tools_selectmethod": "single",
  831. "tools_pathconnect": True,
  832. "tools_paintcontour": True,
  833. "tools_2sided_mirror_axis": "X",
  834. "tools_2sided_axis_loc": "point",
  835. "tools_2sided_drilldia": 0.0393701,
  836. "tools_film_type": 'neg',
  837. "tools_film_boundary": 0.0393701,
  838. "tools_film_scale": 0,
  839. "tools_panelize_spacing_columns": 0,
  840. "tools_panelize_spacing_rows": 0,
  841. "tools_panelize_columns": 1,
  842. "tools_panelize_rows": 1,
  843. "tools_panelize_constrain": False,
  844. "tools_panelize_constrainx": 0.0,
  845. "tools_panelize_constrainy": 0.0,
  846. "tools_panelize_panel_type": 'gerber',
  847. "tools_calc_vshape_tip_dia": 0.007874,
  848. "tools_calc_vshape_tip_angle": 30,
  849. "tools_calc_vshape_cut_z": 0.000787,
  850. "tools_calc_electro_length": 10.0,
  851. "tools_calc_electro_width": 10.0,
  852. "tools_calc_electro_cdensity": 13.0,
  853. "tools_calc_electro_growth": 10.0,
  854. "tools_transform_rotate": 90,
  855. "tools_transform_skew_x": 0.0,
  856. "tools_transform_skew_y": 0.0,
  857. "tools_transform_scale_x": 1.0,
  858. "tools_transform_scale_y": 1.0,
  859. "tools_transform_scale_link": True,
  860. "tools_transform_scale_reference": True,
  861. "tools_transform_offset_x": 0.0,
  862. "tools_transform_offset_y": 0.0,
  863. "tools_transform_mirror_reference": False,
  864. "tools_transform_mirror_point": (0, 0),
  865. "tools_solderpaste_tools": "0.0393701, 0.011811",
  866. "tools_solderpaste_new": 0.011811,
  867. "tools_solderpaste_z_start": 0.00019685039,
  868. "tools_solderpaste_z_dispense": 0.00393701,
  869. "tools_solderpaste_z_stop": 0.00019685039,
  870. "tools_solderpaste_z_travel": 0.00393701,
  871. "tools_solderpaste_z_toolchange": 0.0393701,
  872. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  873. "tools_solderpaste_frxy": 3.0,
  874. "tools_solderpaste_frz": 3.0,
  875. "tools_solderpaste_frz_dispense": 0.0393701,
  876. "tools_solderpaste_speedfwd": 20,
  877. "tools_solderpaste_dwellfwd": 1,
  878. "tools_solderpaste_speedrev": 10,
  879. "tools_solderpaste_dwellrev": 1,
  880. "tools_solderpaste_pp": 'Paste_1',
  881. "tools_sub_close_paths": True
  882. })
  883. # ##############################
  884. # ## Load defaults from file ###
  885. # ##############################
  886. if user_defaults:
  887. self.load_defaults(filename='current_defaults')
  888. # ###########################
  889. # #### APPLY APP LANGUAGE ###
  890. # ###########################
  891. ret_val = fcTranslate.apply_language('strings')
  892. if ret_val == "no language":
  893. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  894. log.debug("Could not find the Language files. The App strings are missing.")
  895. else:
  896. # make the current language the current selection on the language combobox
  897. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  898. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  899. # ##################################
  900. # ### CREATE UNIQUE SERIAL NUMBER ##
  901. # ##################################
  902. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  903. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  904. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  905. self.save_defaults(silent=True)
  906. self.propagate_defaults(silent=True)
  907. self.restore_main_win_geom()
  908. def auto_save_defaults():
  909. try:
  910. self.save_defaults(silent=True)
  911. self.propagate_defaults(silent=True)
  912. finally:
  913. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  914. # the following lines activates automatic defaults save
  915. # if user_defaults:
  916. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  917. # self.options_form = PreferencesUI()
  918. self.options_form_fields = {
  919. "units": self.ui.general_options_form.general_app_group.units_radio,
  920. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  921. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  922. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  923. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  924. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  925. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  926. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  927. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  928. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  929. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  930. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  931. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  932. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  933. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  934. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  935. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  936. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  937. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  938. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  939. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  940. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  941. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  942. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  943. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  944. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  945. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  946. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  947. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  948. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  949. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  950. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  951. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  952. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  953. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  954. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  955. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  956. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  957. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  958. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  959. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  960. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  961. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  962. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  963. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  964. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  965. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  966. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  967. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  968. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  969. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  970. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  971. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  972. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  973. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  974. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  975. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  976. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  977. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  978. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  979. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  980. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  981. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  982. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  983. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  984. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  985. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  986. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  987. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  988. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  989. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  990. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  991. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  992. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  993. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  994. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  995. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  996. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  997. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  998. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  999. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1000. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1001. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1002. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1003. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1004. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1005. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1006. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1007. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1008. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1009. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1010. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1011. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1012. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1013. }
  1014. for name in list(self.postprocessors.keys()):
  1015. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1016. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1017. self.options = LoudDict()
  1018. self.options.set_change_callback(self.on_options_dict_change)
  1019. self.options.update({
  1020. "units": "IN",
  1021. "global_gridx": 1.0,
  1022. "global_gridy": 1.0,
  1023. "global_snap_max": 0.05,
  1024. "global_background_timeout": 300000, # Default value is 5 minutes
  1025. "global_verbose_error_level": 0, # Shell verbosity:
  1026. # 0 = default(python trace only for unknown errors),
  1027. # 1 = show trace(show trace allways), 2 = (For the future).
  1028. "gerber_plot": True,
  1029. "gerber_solid": True,
  1030. "gerber_multicolored": False,
  1031. "gerber_isotooldia": 0.016,
  1032. "gerber_isopasses": 1,
  1033. "gerber_isooverlap": 0.15,
  1034. "gerber_combine_passes": True,
  1035. "gerber_noncoppermargin": 0.0,
  1036. "gerber_noncopperrounded": False,
  1037. "gerber_bboxmargin": 0.0,
  1038. "gerber_bboxrounded": False,
  1039. "excellon_plot": True,
  1040. "excellon_solid": False,
  1041. "excellon_format_upper_in": 2,
  1042. "excellon_format_lower_in": 4,
  1043. "excellon_format_upper_mm": 3,
  1044. "excellon_format_lower_mm": 3,
  1045. "excellon_units": 'INCH',
  1046. "excellon_optimization_type": 'B',
  1047. "excellon_search_time": 3,
  1048. "excellon_zeros": "L",
  1049. "excellon_drillz": -0.1,
  1050. "excellon_travelz": 0.1,
  1051. "excellon_feedrate": 3.0,
  1052. "excellon_feedrate_rapid": 3.0,
  1053. "excellon_spindlespeed": None,
  1054. "excellon_spindledir": 'CW',
  1055. "excellon_dwell": True,
  1056. "excellon_dwelltime": 1000,
  1057. "excellon_toolchange": False,
  1058. "excellon_toolchangez": 1.0,
  1059. "excellon_toolchangexy": "0.0, 0.0",
  1060. "excellon_tooldia": 0.016,
  1061. "excellon_ppname_e": 'default',
  1062. "excellon_f_plunge": False,
  1063. "excellon_startz": None,
  1064. "excellon_endz": 2.0,
  1065. "geometry_plot": True,
  1066. "geometry_segx": 0.0,
  1067. "geometry_segy": 0.0,
  1068. "geometry_cutz": -0.002,
  1069. "geometry_vtipdia": 0.1,
  1070. "geometry_vtipangle": 30,
  1071. "geometry_travelz": 0.1,
  1072. "geometry_feedrate": 3.0,
  1073. "geometry_feedrate_z": 3.0,
  1074. "geometry_feedrate_rapid": 3.0,
  1075. "geometry_spindlespeed": None,
  1076. "geometry_spindledir": 'CW',
  1077. "geometry_dwell": True,
  1078. "geometry_dwelltime": 1000,
  1079. "geometry_cnctooldia": 0.016,
  1080. "geometry_toolchange": False,
  1081. "geometry_toolchangez": 2.0,
  1082. "geometry_toolchangexy": "0.0, 0.0",
  1083. "geometry_startz": None,
  1084. "geometry_endz": 2.0,
  1085. "geometry_ppname_g": "default",
  1086. "geometry_f_plunge": False,
  1087. "geometry_depthperpass": 0.002,
  1088. "geometry_multidepth": False,
  1089. "geometry_extracut": False,
  1090. "cncjob_plot": True,
  1091. "cncjob_tooldia": 0.016,
  1092. "cncjob_prepend": "",
  1093. "cncjob_append": "",
  1094. "tools_ncctools": "1.0, 0.5",
  1095. "tools_nccoverlap": 0.4,
  1096. "tools_nccmargin": 1,
  1097. "tools_cutouttooldia": 0.07,
  1098. "tools_cutoutmargin": 0.1,
  1099. "tools_cutoutgapsize": 0.15,
  1100. "tools_gaps_ff": "8",
  1101. "tools_painttooldia": 0.07,
  1102. "tools_paintoverlap": 0.15,
  1103. "tools_paintmargin": 0.0,
  1104. "tools_paintmethod": "seed",
  1105. "tools_selectmethod": "single",
  1106. "tools_pathconnect": True,
  1107. "tools_paintcontour": True,
  1108. "tools_2sided_mirror_axis": "X",
  1109. "tools_2sided_axis_loc": 'point',
  1110. "tools_2sided_drilldia": 1,
  1111. "tools_film_type": 'neg',
  1112. "tools_film_boundary": 1,
  1113. "tools_film_scale": 0,
  1114. "tools_panelize_spacing_columns": 0,
  1115. "tools_panelize_spacing_rows": 0,
  1116. "tools_panelize_columns": 1,
  1117. "tools_panelize_rows": 1,
  1118. "tools_panelize_constrain": False,
  1119. "tools_panelize_constrainx": 0.0,
  1120. "tools_panelize_constrainy": 0.0
  1121. })
  1122. self.options.update(self.defaults) # Copy app defaults to project options
  1123. self.gen_form = None
  1124. self.ger_form = None
  1125. self.exc_form = None
  1126. self.geo_form = None
  1127. self.cnc_form = None
  1128. self.tools_form = None
  1129. self.on_options_combo_change(0) # Will show the initial form
  1130. # ### Define OBJECT COLLECTION ###
  1131. self.collection = ObjectCollection(self)
  1132. self.ui.project_tab_layout.addWidget(self.collection.view)
  1133. # ################################
  1134. self.log.debug("Finished creating Object Collection.")
  1135. # ### Initialize the color box's color in Preferences -> Global -> Color
  1136. # Init Plot Colors
  1137. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1138. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1139. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1140. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1141. int(self.defaults['global_plot_fill'][7:9], 16))
  1142. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1143. int(self.defaults['global_plot_fill'][7:9], 16))
  1144. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1145. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1146. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1147. # Init Left-Right Selection colors
  1148. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1149. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1150. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1151. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1152. int(self.defaults['global_sel_fill'][7:9], 16))
  1153. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1154. int(self.defaults['global_sel_fill'][7:9], 16))
  1155. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1156. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1157. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1158. # Init Right-Left Selection colors
  1159. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1160. self.defaults['global_alt_sel_fill'])
  1161. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1162. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1163. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1164. int(self.defaults['global_sel_fill'][7:9], 16))
  1165. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1166. int(self.defaults['global_sel_fill'][7:9], 16))
  1167. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1168. self.defaults['global_alt_sel_line'])
  1169. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1170. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1171. # Init Draw color and Selection Draw Color
  1172. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1173. self.defaults['global_draw_color'])
  1174. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1175. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1176. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1177. self.defaults['global_sel_draw_color'])
  1178. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1179. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1180. # Init Project Items color
  1181. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1182. self.defaults['global_proj_item_color'])
  1183. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1184. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1185. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1186. self.defaults['global_proj_item_dis_color'])
  1187. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1188. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1189. # Init the Annotation CNC Job color
  1190. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1191. self.defaults['cncjob_annotation_fontcolor'])
  1192. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1193. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1194. # ### End of Data ####
  1195. # ### Plot Area ####
  1196. start_plot_time = time.time() # debug
  1197. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  1198. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  1199. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  1200. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  1201. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  1202. # Keys over plot enabled
  1203. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  1204. self.ui.splitter.setStretchFactor(1, 2)
  1205. # So it can receive key presses
  1206. self.plotcanvas.vispy_canvas.native.setFocus()
  1207. self.app_cursor = self.plotcanvas.new_cursor()
  1208. self.app_cursor.enabled = False
  1209. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1210. # depending on from where those tools are called different actions can be done
  1211. self.call_source = 'app'
  1212. end_plot_time = time.time()
  1213. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1214. # ### Adjust tabs width ## ##
  1215. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1216. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1217. self.collection.view.setMinimumWidth(290)
  1218. # ### Worker ####
  1219. if self.defaults["global_worker_number"]:
  1220. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1221. else:
  1222. self.workers = WorkerStack(workers_number=2)
  1223. self.worker_task.connect(self.workers.add_task)
  1224. # ### Signal handling ###
  1225. # ### Custom signals ###
  1226. self.inform.connect(self.info)
  1227. self.app_quit.connect(self.quit_application)
  1228. self.message.connect(self.message_dialog)
  1229. self.progress.connect(self.set_progress_bar)
  1230. self.object_created.connect(self.on_object_created)
  1231. self.object_changed.connect(self.on_object_changed)
  1232. self.object_plotted.connect(self.on_object_plotted)
  1233. self.plots_updated.connect(self.on_plots_updated)
  1234. self.file_opened.connect(self.register_recent)
  1235. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1236. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1237. # ### Standard signals
  1238. # ### Menu
  1239. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1240. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1241. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1242. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1243. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1244. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1245. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1246. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1247. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1248. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1249. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1250. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1251. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1252. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1253. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1254. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1255. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1256. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1257. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1258. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1259. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1260. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1261. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1262. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1263. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1264. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1265. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1266. self.ui.menufile_exit.triggered.connect(self.final_save)
  1267. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1268. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1269. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1270. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1271. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1272. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1273. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1274. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1275. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1276. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1277. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1278. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1279. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1280. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1281. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1282. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1283. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1284. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1285. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1286. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1287. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1288. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1289. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1290. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1291. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1292. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1293. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1294. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1295. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1296. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1297. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1298. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1299. self.ui.menuview_zoom_in.triggered.connect(
  1300. lambda: self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  1301. )
  1302. self.ui.menuview_zoom_out.triggered.connect(
  1303. lambda: self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  1304. )
  1305. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1306. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1307. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1308. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1309. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1310. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1311. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1312. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1313. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1314. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1315. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1316. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1317. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1318. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1319. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1320. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1321. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1322. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1323. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1324. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1325. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1326. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1327. # ToolBar signals
  1328. self.connect_toolbar_signals()
  1329. # Notebook signals
  1330. # make the right click on the notebook tab connect to a function
  1331. self.ui.notebook.setupContextMenu()
  1332. self.ui.notebook.addContextMenu(
  1333. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1334. initial_checked=self.defaults["global_tabs_detachable"])
  1335. # activate initial state
  1336. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1337. # Plot Tab Area signals
  1338. # make the right click on the plot area tab connect to a function
  1339. self.ui.plot_tab_area.setupContextMenu()
  1340. self.ui.plot_tab_area.addContextMenu(
  1341. _("Detachable Tabs"), self.on_plot_area_tab_rmb_click,
  1342. initial_checked=self.defaults["global_tabs_detachable"])
  1343. # activate initial state
  1344. self.on_plot_area_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1345. # Context Menu
  1346. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1347. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1348. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1349. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1350. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1351. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1352. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1353. self.ui.clearplot.triggered.connect(self.clear_plots)
  1354. self.ui.replot.triggered.connect(self.plot_all)
  1355. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1356. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1357. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1358. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1359. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1360. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1361. # Preferences Plot Area TAB
  1362. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1363. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1364. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1365. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1366. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1367. # ##############################
  1368. # ### GUI PREFERENCES SIGNALS ##
  1369. # ##############################
  1370. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1371. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1372. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1373. )
  1374. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1375. lambda: self.on_toggle_units(no_pref=False))
  1376. # ##############################
  1377. # ### GUI PREFERENCES SIGNALS ##
  1378. # ##############################
  1379. # Setting plot colors signals
  1380. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1381. self.on_pf_color_entry)
  1382. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1383. self.on_pf_color_button)
  1384. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1385. self.on_pf_color_spinner)
  1386. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1387. self.on_pf_color_slider)
  1388. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1389. self.on_pl_color_entry)
  1390. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1391. self.on_pl_color_button)
  1392. # Setting selection (left - right) colors signals
  1393. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1394. self.on_sf_color_entry)
  1395. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1396. self.on_sf_color_button)
  1397. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1398. self.on_sf_color_spinner)
  1399. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1400. self.on_sf_color_slider)
  1401. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1402. self.on_sl_color_entry)
  1403. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1404. self.on_sl_color_button)
  1405. # Setting selection (right - left) colors signals
  1406. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1407. self.on_alt_sf_color_entry)
  1408. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1409. self.on_alt_sf_color_button)
  1410. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1411. self.on_alt_sf_color_spinner)
  1412. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1413. self.on_alt_sf_color_slider)
  1414. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1415. self.on_alt_sl_color_entry)
  1416. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1417. self.on_alt_sl_color_button)
  1418. # Setting Editor Draw colors signals
  1419. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1420. self.on_draw_color_entry)
  1421. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1422. self.on_draw_color_button)
  1423. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1424. self.on_sel_draw_color_entry)
  1425. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1426. self.on_sel_draw_color_button)
  1427. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1428. self.on_proj_color_entry)
  1429. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1430. self.on_proj_color_button)
  1431. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1432. self.on_proj_color_dis_entry)
  1433. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1434. self.on_proj_color_dis_button)
  1435. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1436. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1437. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1438. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1439. self.on_cnc_custom_parameters)
  1440. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1441. self.on_annotation_fontcolor_entry)
  1442. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1443. self.on_annotation_fontcolor_button)
  1444. # Modify G-CODE Plot Area TAB
  1445. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1446. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1447. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1448. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1449. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1450. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1451. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1452. # Object list
  1453. self.collection.view.activated.connect(self.on_row_activated)
  1454. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1455. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1456. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1457. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1458. self.on_excellon_defaults_button)
  1459. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1460. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1461. self.on_excellon_options_button)
  1462. # when there are arguments at application startup this get launched
  1463. self.args_at_startup.connect(self.on_startup_args)
  1464. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1465. self.tool_tab_locked = False
  1466. # decide if to show or hide the Notebook side of the screen at startup
  1467. if self.defaults["global_project_at_startup"] is True:
  1468. self.ui.splitter.setSizes([1, 1])
  1469. else:
  1470. self.ui.splitter.setSizes([0, 1])
  1471. # ###################
  1472. # ### Other setups ##
  1473. # ###################
  1474. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1475. self.setup_obj_classes()
  1476. self.setup_recent_items()
  1477. self.setup_component_editor()
  1478. # ############
  1479. # ### Shell ##
  1480. # ############
  1481. # #########################
  1482. # Auto-complete KEYWORDS ##
  1483. # #########################
  1484. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1485. 'aligndrill', 'clear',
  1486. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1487. 'export_gcode',
  1488. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1489. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1490. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1491. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1492. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1493. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1494. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1495. ]
  1496. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1497. 'holes', 'grid', 'minoffset', 'gridoffset', 'axisoffset', 'dia', 'dist',
  1498. 'gridoffsetx', 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate',
  1499. 'feedrate_rapid', 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g',
  1500. 'outname', 'margin', 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed',
  1501. 'toolchange', 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble',
  1502. 'filename', 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads',
  1503. 'x', 'y', 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value',
  1504. 'angle_x', 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1505. ]
  1506. self.tcl_keywords = [
  1507. "after", "append", "apply", "array", "auto_execok", "auto_import", "auto_load", "auto_mkindex",
  1508. "auto_qualify", "auto_reset", "bgerror", "binary", "break", "case", "catch", "cd", "chan", "clock", "close",
  1509. "concat", "continue", "coroutine", "dict", "encoding", "eof", "error", "eval", "exec", "exit", "expr",
  1510. "fblocked", "fconfigure", "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets", "glob",
  1511. "global", "history", "if", "incr", "info", "interp", "join", "lappend", "lassign", "lindex", "linsert",
  1512. "list", "llength", "load", "lrange", "lrepeat", "lreplace", "lreverse", "lsearch", "lset", "lsort",
  1513. "mathfunc", "mathop", "memory", "my", "namespace", "next", "nextto", "open", "package", "parray", "pid",
  1514. "pkg_mkIndex", "platform", "proc", "puts", "pwd", "read", "refchan", "regexp", "regsub", "rename", "return",
  1515. "scan", "seek", "self", "set", "socket", "source", "split", "string", "subst", "switch", "tailcall",
  1516. "tcl_endOfWord", "tcl_findLibrary", "tcl_startOfNextWord", "tcl_startOfPreviousWord", "tcl_wordBreakAfter",
  1517. "tcl_wordBreakBefore", "tell", "throw", "time", "tm", "trace", "transchan", "try", "unknown", "unload",
  1518. "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield", "yieldto", "zlib",
  1519. "attemptckalloc", "attemptckrealloc", "ckalloc", "ckfree", "ckrealloc", "Tcl_Access", "Tcl_AddErrorInfo",
  1520. "Tcl_AddObjErrorInfo", "Tcl_AlertNotifier", "Tcl_Alloc", "Tcl_AllocStatBuf", "Tcl_AllowExceptions",
  1521. "Tcl_AppendAllObjTypes", "Tcl_AppendElement", "Tcl_AppendExportList", "Tcl_AppendFormatToObj",
  1522. "Tcl_AppendLimitedToObj", "Tcl_AppendObjToErrorInfo", "Tcl_AppendObjToObj", "Tcl_AppendPrintfToObj",
  1523. "Tcl_AppendResult", "Tcl_AppendResultVA", "Tcl_AppendStringsToObj", "Tcl_AppendStringsToObjVA",
  1524. "Tcl_AppendToObj", "Tcl_AppendUnicodeToObj", "Tcl_AppInit", "Tcl_AsyncCreate", "Tcl_AsyncDelete",
  1525. "Tcl_AsyncInvoke", "Tcl_AsyncMark", "Tcl_AsyncReady", "Tcl_AttemptAlloc", "Tcl_AttemptRealloc",
  1526. "Tcl_AttemptSetObjLength", "Tcl_BackgroundError", "Tcl_BackgroundException", "Tcl_Backslash",
  1527. "Tcl_BadChannelOption", "Tcl_CallWhenDeleted", "Tcl_Canceled", "Tcl_CancelEval", "Tcl_CancelIdleCall",
  1528. "Tcl_ChannelBlockModeProc", "Tcl_ChannelBuffered", "Tcl_ChannelClose2Proc", "Tcl_ChannelCloseProc",
  1529. "Tcl_ChannelFlushProc", "Tcl_ChannelGetHandleProc", "Tcl_ChannelGetOptionProc", "Tcl_ChannelHandlerProc",
  1530. "Tcl_ChannelInputProc", "Tcl_ChannelName", "Tcl_ChannelOutputProc", "Tcl_ChannelSeekProc",
  1531. "Tcl_ChannelSetOptionProc", "Tcl_ChannelThreadActionProc", "Tcl_ChannelTruncateProc", "Tcl_ChannelVersion",
  1532. "Tcl_ChannelWatchProc", "Tcl_ChannelWideSeekProc", "Tcl_Chdir", "Tcl_ClassGetMetadata",
  1533. "Tcl_ClassSetConstructor", "Tcl_ClassSetDestructor", "Tcl_ClassSetMetadata", "Tcl_ClearChannelHandlers",
  1534. "Tcl_Close", "Tcl_CommandComplete", "Tcl_CommandTraceInfo", "Tcl_Concat", "Tcl_ConcatObj",
  1535. "Tcl_ConditionFinalize", "Tcl_ConditionNotify", "Tcl_ConditionWait", "Tcl_ConvertCountedElement",
  1536. "Tcl_ConvertElement", "Tcl_ConvertToType", "Tcl_CopyObjectInstance", "Tcl_CreateAlias",
  1537. "Tcl_CreateAliasObj", "Tcl_CreateChannel", "Tcl_CreateChannelHandler", "Tcl_CreateCloseHandler",
  1538. "Tcl_CreateCommand", "Tcl_CreateEncoding", "Tcl_CreateEnsemble", "Tcl_CreateEventSource",
  1539. "Tcl_CreateExitHandler", "Tcl_CreateFileHandler", "Tcl_CreateHashEntry", "Tcl_CreateInterp",
  1540. "Tcl_CreateMathFunc", "Tcl_CreateNamespace", "Tcl_CreateObjCommand", "Tcl_CreateObjTrace",
  1541. "Tcl_CreateSlave", "Tcl_CreateThread", "Tcl_CreateThreadExitHandler", "Tcl_CreateTimerHandler",
  1542. "Tcl_CreateTrace", "Tcl_CutChannel", "Tcl_DecrRefCount", "Tcl_DeleteAssocData", "Tcl_DeleteChannelHandler",
  1543. "Tcl_DeleteCloseHandler", "Tcl_DeleteCommand", "Tcl_DeleteCommandFromToken", "Tcl_DeleteEvents",
  1544. "Tcl_DeleteEventSource", "Tcl_DeleteExitHandler", "Tcl_DeleteFileHandler", "Tcl_DeleteHashEntry",
  1545. "Tcl_DeleteHashTable", "Tcl_DeleteInterp", "Tcl_DeleteNamespace", "Tcl_DeleteThreadExitHandler",
  1546. "Tcl_DeleteTimerHandler", "Tcl_DeleteTrace", "Tcl_DetachChannel", "Tcl_DetachPids", "Tcl_DictObjDone",
  1547. "Tcl_DictObjFirst", "Tcl_DictObjGet", "Tcl_DictObjNext", "Tcl_DictObjPut", "Tcl_DictObjPutKeyList",
  1548. "Tcl_DictObjRemove", "Tcl_DictObjRemoveKeyList", "Tcl_DictObjSize", "Tcl_DiscardInterpState",
  1549. "Tcl_DiscardResult", "Tcl_DontCallWhenDeleted", "Tcl_DoOneEvent", "Tcl_DoWhenIdle", "Tcl_DStringAppend",
  1550. "Tcl_DStringAppendElement", "Tcl_DStringEndSublist", "Tcl_DStringFree", "Tcl_DStringGetResult",
  1551. "Tcl_DStringInit", "Tcl_DStringLength", "Tcl_DStringResult", "Tcl_DStringSetLength",
  1552. "Tcl_DStringStartSublist", "Tcl_DStringTrunc", "Tcl_DStringValue", "Tcl_DumpActiveMemory",
  1553. "Tcl_DuplicateObj", "Tcl_Eof", "Tcl_ErrnoId", "Tcl_ErrnoMsg", "Tcl_Eval", "Tcl_EvalEx", "Tcl_EvalFile",
  1554. "Tcl_EvalObjEx", "Tcl_EvalObjv", "Tcl_EvalTokens", "Tcl_EvalTokensStandard", "Tcl_EventuallyFree",
  1555. "Tcl_Exit", "Tcl_ExitThread", "Tcl_Export", "Tcl_ExposeCommand", "Tcl_ExprBoolean", "Tcl_ExprBooleanObj",
  1556. "Tcl_ExprDouble", "Tcl_ExprDoubleObj", "Tcl_ExprLong", "Tcl_ExprLongObj", "Tcl_ExprObj", "Tcl_ExprString",
  1557. "Tcl_ExternalToUtf", "Tcl_ExternalToUtfDString", "Tcl_Finalize", "Tcl_FinalizeNotifier",
  1558. "Tcl_FinalizeThread", "Tcl_FindCommand", "Tcl_FindEnsemble", "Tcl_FindExecutable", "Tcl_FindHashEntry",
  1559. "Tcl_FindNamespace", "Tcl_FirstHashEntry", "Tcl_Flush", "Tcl_ForgetImport", "Tcl_Format",
  1560. "Tcl_Free· Tcl_FreeEncoding", "Tcl_FreeParse", "Tcl_FreeResult", "Tcl_FSAccess", "Tcl_FSChdir",
  1561. "Tcl_FSConvertToPathType", "Tcl_FSCopyDirectory", "Tcl_FSCopyFile", "Tcl_FSCreateDirectory", "Tcl_FSData",
  1562. "Tcl_FSDeleteFile", "Tcl_FSEqualPaths", "Tcl_FSEvalFile", "Tcl_FSEvalFileEx", "Tcl_FSFileAttrsGet",
  1563. "Tcl_FSFileAttrsSet", "Tcl_FSFileAttrStrings", "Tcl_FSFileSystemInfo", "Tcl_FSGetCwd",
  1564. "Tcl_FSGetFileSystemForPath", "Tcl_FSGetInternalRep", "Tcl_FSGetNativePath", "Tcl_FSGetNormalizedPath",
  1565. "Tcl_FSGetPathType", "Tcl_FSGetTranslatedPath", "Tcl_FSGetTranslatedStringPath", "Tcl_FSJoinPath",
  1566. "Tcl_FSJoinToPath", "Tcl_FSLink· Tcl_FSListVolumes", "Tcl_FSLoadFile", "Tcl_FSLstat",
  1567. "Tcl_FSMatchInDirectory", "Tcl_FSMountsChanged", "Tcl_FSNewNativePath", "Tcl_FSOpenFileChannel",
  1568. "Tcl_FSPathSeparator", "Tcl_FSRegister", "Tcl_FSRemoveDirectory", "Tcl_FSRenameFile", "Tcl_FSSplitPath",
  1569. "Tcl_FSStat", "Tcl_FSUnloadFile", "Tcl_FSUnregister", "Tcl_FSUtime", "Tcl_GetAccessTimeFromStat",
  1570. "Tcl_GetAlias", "Tcl_GetAliasObj", "Tcl_GetAssocData", "Tcl_GetBignumFromObj", "Tcl_GetBlocksFromStat",
  1571. "Tcl_GetBlockSizeFromStat", "Tcl_GetBoolean", "Tcl_GetBooleanFromObj", "Tcl_GetByteArrayFromObj",
  1572. "Tcl_GetChangeTimeFromStat", "Tcl_GetChannel", "Tcl_GetChannelBufferSize", "Tcl_GetChannelError",
  1573. "Tcl_GetChannelErrorInterp", "Tcl_GetChannelHandle", "Tcl_GetChannelInstanceData", "Tcl_GetChannelMode",
  1574. "Tcl_GetChannelName", "Tcl_GetChannelNames", "Tcl_GetChannelNamesEx", "Tcl_GetChannelOption",
  1575. "Tcl_GetChannelThread", "Tcl_GetChannelType", "Tcl_GetCharLength", "Tcl_GetClassAsObject",
  1576. "Tcl_GetCommandFromObj", "Tcl_GetCommandFullName", "Tcl_GetCommandInfo", "Tcl_GetCommandInfoFromToken",
  1577. "Tcl_GetCommandName", "Tcl_GetCurrentNamespace", "Tcl_GetCurrentThread", "Tcl_GetCwd",
  1578. "Tcl_GetDefaultEncodingDir", "Tcl_GetDeviceTypeFromStat", "Tcl_GetDouble", "Tcl_GetDoubleFromObj",
  1579. "Tcl_GetEncoding", "Tcl_GetEncodingFromObj", "Tcl_GetEncodingName", "Tcl_GetEncodingNameFromEnvironment",
  1580. "Tcl_GetEncodingNames", "Tcl_GetEncodingSearchPath", "Tcl_GetEnsembleFlags", "Tcl_GetEnsembleMappingDict",
  1581. "Tcl_GetEnsembleNamespace", "Tcl_GetEnsembleParameterList", "Tcl_GetEnsembleSubcommandList",
  1582. "Tcl_GetEnsembleUnknownHandler", "Tcl_GetErrno", "Tcl_GetErrorLine", "Tcl_GetFSDeviceFromStat",
  1583. "Tcl_GetFSInodeFromStat", "Tcl_GetGlobalNamespace", "Tcl_GetGroupIdFromStat", "Tcl_GetHashKey",
  1584. "Tcl_GetHashValue", "Tcl_GetHostName", "Tcl_GetIndexFromObj", "Tcl_GetIndexFromObjStruct", "Tcl_GetInt",
  1585. "Tcl_GetInterpPath", "Tcl_GetIntFromObj", "Tcl_GetLinkCountFromStat", "Tcl_GetLongFromObj", "Tcl_GetMaster",
  1586. "Tcl_GetMathFuncInfo", "Tcl_GetModeFromStat", "Tcl_GetModificationTimeFromStat", "Tcl_GetNameOfExecutable",
  1587. "Tcl_GetNamespaceUnknownHandler", "Tcl_GetObjectAsClass", "Tcl_GetObjectCommand", "Tcl_GetObjectFromObj",
  1588. "Tcl_GetObjectName", "Tcl_GetObjectNamespace", "Tcl_GetObjResult", "Tcl_GetObjType", "Tcl_GetOpenFile",
  1589. "Tcl_GetPathType", "Tcl_GetRange", "Tcl_GetRegExpFromObj", "Tcl_GetReturnOptions", "Tcl_Gets",
  1590. "Tcl_GetServiceMode", "Tcl_GetSizeFromStat", "Tcl_GetSlave", "Tcl_GetsObj", "Tcl_GetStackedChannel",
  1591. "Tcl_GetStartupScript", "Tcl_GetStdChannel", "Tcl_GetString", "Tcl_GetStringFromObj", "Tcl_GetStringResult",
  1592. "Tcl_GetThreadData", "Tcl_GetTime", "Tcl_GetTopChannel", "Tcl_GetUniChar", "Tcl_GetUnicode",
  1593. "Tcl_GetUnicodeFromObj", "Tcl_GetUserIdFromStat", "Tcl_GetVar", "Tcl_GetVar2", "Tcl_GetVar2Ex",
  1594. "Tcl_GetVersion", "Tcl_GetWideIntFromObj", "Tcl_GlobalEval", "Tcl_GlobalEvalObj", "Tcl_HashStats",
  1595. "Tcl_HideCommand", "Tcl_Import", "Tcl_IncrRefCount", "Tcl_Init", "Tcl_InitCustomHashTable",
  1596. "Tcl_InitHashTable", "Tcl_InitMemory", "Tcl_InitNotifier", "Tcl_InitObjHashTable", "Tcl_InitStubs",
  1597. "Tcl_InputBlocked", "Tcl_InputBuffered", "Tcl_InterpActive", "Tcl_InterpDeleted", "Tcl_InvalidateStringRep",
  1598. "Tcl_IsChannelExisting", "Tcl_IsChannelRegistered", "Tcl_IsChannelShared", "Tcl_IsEnsemble", "Tcl_IsSafe",
  1599. "Tcl_IsShared", "Tcl_IsStandardChannel", "Tcl_JoinPath", "Tcl_JoinThread", "Tcl_LimitAddHandler",
  1600. "Tcl_LimitCheck", "Tcl_LimitExceeded", "Tcl_LimitGetCommands", "Tcl_LimitGetGranularity",
  1601. "Tcl_LimitGetTime", "Tcl_LimitReady", "Tcl_LimitRemoveHandler", "Tcl_LimitSetCommands",
  1602. "Tcl_LimitSetGranularity", "Tcl_LimitSetTime", "Tcl_LimitTypeEnabled", "Tcl_LimitTypeExceeded",
  1603. "Tcl_LimitTypeReset", "Tcl_LimitTypeSet", "Tcl_LinkVar", "Tcl_ListMathFuncs", "Tcl_ListObjAppendElement",
  1604. "Tcl_ListObjAppendList", "Tcl_ListObjGetElements", "Tcl_ListObjIndex", "Tcl_ListObjLength",
  1605. "Tcl_ListObjReplace", "Tcl_LogCommandInfo", "Tcl_Main", "Tcl_MakeFileChannel", "Tcl_MakeSafe",
  1606. "Tcl_MakeTcpClientChannel", "Tcl_Merge", "Tcl_MethodDeclarerClass", "Tcl_MethodDeclarerObject",
  1607. "Tcl_MethodIsPublic", "Tcl_MethodIsType", "Tcl_MethodName", "Tcl_MutexFinalize", "Tcl_MutexLock",
  1608. "Tcl_MutexUnlock", "Tcl_NewBignumObj", "Tcl_NewBooleanObj", "Tcl_NewByteArrayObj", "Tcl_NewDictObj",
  1609. "Tcl_NewDoubleObj", "Tcl_NewInstanceMethod", "Tcl_NewIntObj", "Tcl_NewListObj", "Tcl_NewLongObj",
  1610. "Tcl_NewMethod", "Tcl_NewObj", "Tcl_NewObjectInstance", "Tcl_NewStringObj", "Tcl_NewUnicodeObj",
  1611. "Tcl_NewWideIntObj", "Tcl_NextHashEntry", "Tcl_NotifyChannel", "Tcl_NRAddCallback", "Tcl_NRCallObjProc",
  1612. "Tcl_NRCmdSwap", "Tcl_NRCreateCommand", "Tcl_NREvalObj", "Tcl_NREvalObjv", "Tcl_NumUtfChars",
  1613. "Tcl_ObjectContextInvokeNext", "Tcl_ObjectContextIsFiltering", "Tcl_ObjectContextMethod",
  1614. "Tcl_ObjectContextObject", "Tcl_ObjectContextSkippedArgs", "Tcl_ObjectDeleted", "Tcl_ObjectGetMetadata",
  1615. "Tcl_ObjectGetMethodNameMapper", "Tcl_ObjectSetMetadata", "Tcl_ObjectSetMethodNameMapper", "Tcl_ObjGetVar2",
  1616. "Tcl_ObjPrintf", "Tcl_ObjSetVar2", "Tcl_OpenCommandChannel", "Tcl_OpenFileChannel", "Tcl_OpenTcpClient",
  1617. "Tcl_OpenTcpServer", "Tcl_OutputBuffered", "Tcl_Panic", "Tcl_PanicVA", "Tcl_ParseArgsObjv",
  1618. "Tcl_ParseBraces", "Tcl_ParseCommand", "Tcl_ParseExpr", "Tcl_ParseQuotedString", "Tcl_ParseVar",
  1619. "Tcl_ParseVarName", "Tcl_PkgPresent", "Tcl_PkgPresentEx", "Tcl_PkgProvide", "Tcl_PkgProvideEx",
  1620. "Tcl_PkgRequire", "Tcl_PkgRequireEx", "Tcl_PkgRequireProc", "Tcl_PosixError", "Tcl_Preserve",
  1621. "Tcl_PrintDouble", "Tcl_PutEnv", "Tcl_QueryTimeProc", "Tcl_QueueEvent", "Tcl_Read", "Tcl_ReadChars",
  1622. "Tcl_ReadRaw", "Tcl_Realloc", "Tcl_ReapDetachedProcs", "Tcl_RecordAndEval", "Tcl_RecordAndEvalObj",
  1623. "Tcl_RegExpCompile", "Tcl_RegExpExec", "Tcl_RegExpExecObj", "Tcl_RegExpGetInfo", "Tcl_RegExpMatch",
  1624. "Tcl_RegExpMatchObj", "Tcl_RegExpRange", "Tcl_RegisterChannel", "Tcl_RegisterConfig", "Tcl_RegisterObjType",
  1625. "Tcl_Release", "Tcl_ResetResult", "Tcl_RestoreInterpState", "Tcl_RestoreResult", "Tcl_SaveInterpState",
  1626. "Tcl_SaveResult", "Tcl_ScanCountedElement", "Tcl_ScanElement", "Tcl_Seek", "Tcl_ServiceAll",
  1627. "Tcl_ServiceEvent", "Tcl_ServiceModeHook", "Tcl_SetAssocData", "Tcl_SetBignumObj", "Tcl_SetBooleanObj",
  1628. "Tcl_SetByteArrayLength", "Tcl_SetByteArrayObj", "Tcl_SetChannelBufferSize", "Tcl_SetChannelError",
  1629. "Tcl_SetChannelErrorInterp", "Tcl_SetChannelOption", "Tcl_SetCommandInfo", "Tcl_SetCommandInfoFromToken",
  1630. "Tcl_SetDefaultEncodingDir", "Tcl_SetDoubleObj", "Tcl_SetEncodingSearchPath", "Tcl_SetEnsembleFlags",
  1631. "Tcl_SetEnsembleMappingDict", "Tcl_SetEnsembleParameterList", "Tcl_SetEnsembleSubcommandList",
  1632. "Tcl_SetEnsembleUnknownHandler", "Tcl_SetErrno", "Tcl_SetErrorCode", "Tcl_SetErrorCodeVA",
  1633. "Tcl_SetErrorLine", "Tcl_SetExitProc", "Tcl_SetHashValue", "Tcl_SetIntObj", "Tcl_SetListObj",
  1634. "Tcl_SetLongObj", "Tcl_SetMainLoop", "Tcl_SetMaxBlockTime", "Tcl_SetNamespaceUnknownHandler",
  1635. "Tcl_SetNotifier", "Tcl_SetObjErrorCode", "Tcl_SetObjLength", "Tcl_SetObjResult", "Tcl_SetPanicProc",
  1636. "Tcl_SetRecursionLimit", "Tcl_SetResult", "Tcl_SetReturnOptions", "Tcl_SetServiceMode",
  1637. "Tcl_SetStartupScript", "Tcl_SetStdChannel", "Tcl_SetStringObj", "Tcl_SetSystemEncoding", "Tcl_SetTimeProc",
  1638. "Tcl_SetTimer", "Tcl_SetUnicodeObj", "Tcl_SetVar", "Tcl_SetVar2", "Tcl_SetVar2Ex", "Tcl_SetWideIntObj",
  1639. "Tcl_SignalId", "Tcl_SignalMsg", "Tcl_Sleep", "Tcl_SourceRCFile", "Tcl_SpliceChannel", "Tcl_SplitList",
  1640. "Tcl_SplitPath", "Tcl_StackChannel", "Tcl_StandardChannels", "Tcl_Stat", "Tcl_StaticPackage",
  1641. "Tcl_StringCaseMatch", "Tcl_StringMatch", "Tcl_SubstObj", "Tcl_TakeBignumFromObj", "Tcl_Tell",
  1642. "Tcl_ThreadAlert", "Tcl_ThreadQueueEvent", "Tcl_TraceCommand", "Tcl_TraceVar", "Tcl_TraceVar2",
  1643. "Tcl_TransferResult", "Tcl_TranslateFileName", "Tcl_TruncateChannel", "Tcl_Ungets", "Tcl_UniChar",
  1644. "Tcl_UniCharAtIndex", "Tcl_UniCharCaseMatch", "Tcl_UniCharIsAlnum", "Tcl_UniCharIsAlpha",
  1645. "Tcl_UniCharIsControl", "Tcl_UniCharIsDigit", "Tcl_UniCharIsGraph", "Tcl_UniCharIsLower",
  1646. "Tcl_UniCharIsPrint", "Tcl_UniCharIsPunct", "Tcl_UniCharIsSpace", "Tcl_UniCharIsUpper",
  1647. "Tcl_UniCharIsWordChar", "Tcl_UniCharLen", "Tcl_UniCharNcasecmp", "Tcl_UniCharNcmp", "Tcl_UniCharToLower",
  1648. "Tcl_UniCharToTitle", "Tcl_UniCharToUpper", "Tcl_UniCharToUtf", "Tcl_UniCharToUtfDString", "Tcl_UnlinkVar",
  1649. "Tcl_UnregisterChannel", "Tcl_UnsetVar", "Tcl_UnsetVar2", "Tcl_UnstackChannel", "Tcl_UntraceCommand",
  1650. "Tcl_UntraceVar", "Tcl_UntraceVar2", "Tcl_UpdateLinkedVar", "Tcl_UpVar", "Tcl_UpVar2", "Tcl_UtfAtIndex",
  1651. "Tcl_UtfBackslash", "Tcl_UtfCharComplete", "Tcl_UtfFindFirst", "Tcl_UtfFindLast", "Tcl_UtfNext",
  1652. "Tcl_UtfPrev", "Tcl_UtfToExternal", "Tcl_UtfToExternalDString", "Tcl_UtfToLower", "Tcl_UtfToTitle",
  1653. "Tcl_UtfToUniChar", "Tcl_UtfToUniCharDString", "Tcl_UtfToUpper", "Tcl_ValidateAllMemory", "Tcl_VarEval",
  1654. "Tcl_VarEvalVA", "Tcl_VarTraceInfo", "Tcl_VarTraceInfo2", "Tcl_WaitForEvent", "Tcl_WaitPid",
  1655. "Tcl_WinTCharToUtf", "Tcl_WinUtfToTChar", "Tcl_Write", "Tcl_WriteChars", "Tcl_WriteObj", "Tcl_WriteRaw",
  1656. "Tcl_WrongNumArgs", "Tcl_ZlibAdler32", "Tcl_ZlibCRC32", "Tcl_ZlibDeflate", "Tcl_ZlibInflate",
  1657. "Tcl_ZlibStreamChecksum", "Tcl_ZlibStreamClose", "Tcl_ZlibStreamEof", "Tcl_ZlibStreamGet",
  1658. "Tcl_ZlibStreamGetCommandName", "Tcl_ZlibStreamInit", "Tcl_ZlibStreamPut", "dde", "http", "msgcat",
  1659. "registry", "tcltest", "Tcl_AllocHashEntryProc", "Tcl_AppInitProc", "Tcl_ArgvInfo", "Tcl_AsyncProc",
  1660. "Tcl_ChannelProc", "Tcl_ChannelType", "Tcl_CloneProc", "Tcl_CloseProc", "Tcl_CmdDeleteProc", "Tcl_CmdInfo",
  1661. "Tcl_CmdObjTraceDeleteProc", "Tcl_CmdObjTraceProc", "Tcl_CmdProc", "Tcl_CmdTraceProc",
  1662. "Tcl_CommandTraceProc", "Tcl_CompareHashKeysProc", "Tcl_Config", "Tcl_DriverBlockModeProc",
  1663. "Tcl_DriverClose2Proc", "Tcl_DriverCloseProc", "Tcl_DriverFlushProc", "Tcl_DriverGetHandleProc",
  1664. "Tcl_DriverGetOptionProc", "Tcl_DriverHandlerProc", "Tcl_DriverInputProc", "Tcl_DriverOutputProc",
  1665. "Tcl_DriverSeekProc", "Tcl_DriverSetOptionProc", "Tcl_DriverThreadActionProc", "Tcl_DriverTruncateProc",
  1666. "Tcl_DriverWatchProc", "Tcl_DriverWideSeekProc", "Tcl_DupInternalRepProc", "Tcl_EncodingConvertProc",
  1667. "Tcl_EncodingFreeProc", "Tcl_EncodingType", "Tcl_Event", "Tcl_EventCheckProc", "Tcl_EventDeleteProc",
  1668. "Tcl_EventProc", "Tcl_EventSetupProc", "Tcl_ExitProc", "Tcl_FileProc", "Tcl_Filesystem",
  1669. "Tcl_FreeHashEntryProc", "Tcl_FreeInternalRepProc", "Tcl_FreeProc", "Tcl_FSAccessProc", "Tcl_FSChdirProc",
  1670. "Tcl_FSCopyDirectoryProc", "Tcl_FSCopyFileProc", "Tcl_FSCreateDirectoryProc", "Tcl_FSCreateInternalRepProc",
  1671. "Tcl_FSDeleteFileProc", "Tcl_FSDupInternalRepProc", "Tcl_FSFileAttrsGetProc", "Tcl_FSFileAttrsSetProc",
  1672. "Tcl_FSFilesystemPathTypeProc", "Tcl_FSFilesystemSeparatorProc", "Tcl_FSFreeInternalRepProc",
  1673. "Tcl_FSGetCwdProc", "Tcl_FSInternalToNormalizedProc", "Tcl_FSLinkProc", "Tcl_FSListVolumesProc",
  1674. "Tcl_FSLoadFileProc", "Tcl_FSLstatProc", "Tcl_FSMatchInDirectoryProc", "Tcl_FSNormalizePathProc",
  1675. "Tcl_FSOpenFileChannelProc", "Tcl_FSPathInFilesystemProc", "Tcl_FSRemoveDirectoryProc",
  1676. "Tcl_FSRenameFileProc", "Tcl_FSStatProc", "Tcl_FSUnloadFileProc", "Tcl_FSUtimeProc", "Tcl_GlobTypeData",
  1677. "Tcl_HashKeyType", "Tcl_IdleProc", "Tcl_Interp", "Tcl_InterpDeleteProc", "Tcl_LimitHandlerDeleteProc",
  1678. "Tcl_LimitHandlerProc", "Tcl_MainLoopProc", "Tcl_MathProc", "Tcl_MethodCallProc", "Tcl_MethodDeleteProc",
  1679. "Tcl_MethodType", "Tcl_NamespaceDeleteProc", "Tcl_NotifierProcs", "Tcl_Obj", "Tcl_ObjCmdProc",
  1680. "Tcl_ObjectMapMethodNameProc", "Tcl_ObjectMetadataDeleteProc", "Tcl_ObjType", "Tcl_PackageInitProc",
  1681. "Tcl_PackageUnloadProc", "Tcl_PanicProc", "Tcl_RegExpIndices", "Tcl_RegExpInfo", "Tcl_ScaleTimeProc",
  1682. "Tcl_SetFromAnyProc", "Tcl_TcpAcceptProc", "Tcl_Time", "Tcl_TimerProc", "Tcl_Token", "Tcl_UpdateStringProc",
  1683. "Tcl_Value", "Tcl_VarTraceProc", "argc", "argv", "argv0", "auto_path", "env", "errorCode", "errorInfo",
  1684. "filename", "re_syntax", "safe", "Tcl", "tcl_interactive", "tcl_library", "TCL_MEM_DEBUG",
  1685. "tcl_nonwordchars", "tcl_patchLevel", "tcl_pkgPath", "tcl_platform", "tcl_precision", "tcl_rcFileName",
  1686. "tcl_traceCompile", "tcl_traceEval", "tcl_version", "tcl_wordchars"
  1687. ]
  1688. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1689. self.shell = FCShell(self, version=self.version)
  1690. self.shell._edit.set_model_data(self.myKeywords)
  1691. self.ui.code_editor.set_model_data(self.myKeywords)
  1692. self.shell.setWindowIcon(self.ui.app_icon)
  1693. self.shell.setWindowTitle("FlatCAM Shell")
  1694. self.shell.resize(*self.defaults["global_shell_shape"])
  1695. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1696. self.shell.append_output(_("(Type help to get started)\n\n"))
  1697. self.init_tcl()
  1698. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1699. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1700. self.ui.shell_dock.setWidget(self.shell)
  1701. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1702. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1703. QtWidgets.QDockWidget.DockWidgetFloatable |
  1704. QtWidgets.QDockWidget.DockWidgetClosable)
  1705. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1706. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1707. if self.defaults["global_shell_at_startup"]:
  1708. self.ui.shell_dock.show()
  1709. else:
  1710. self.ui.shell_dock.hide()
  1711. # ########################
  1712. # ### Tools and Plugins ##
  1713. # ########################
  1714. self.dblsidedtool = None
  1715. self.measurement_tool = None
  1716. self.panelize_tool = None
  1717. self.film_tool = None
  1718. self.paste_tool = None
  1719. self.calculator_tool = None
  1720. self.sub_tool = None
  1721. self.move_tool = None
  1722. self.cutout_tool = None
  1723. self.ncclear_tool = None
  1724. self.paint_tool = None
  1725. self.transform_tool = None
  1726. self.properties_tool = None
  1727. self.pdf_tool = None
  1728. self.image_tool = None
  1729. self.pcb_wizard_tool = None
  1730. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1731. self.install_tools()
  1732. # ### System Font Parsing ###
  1733. # self.f_parse = ParseFont(self)
  1734. # self.parse_system_fonts()
  1735. # test if the program was started with a script as parameter
  1736. if self.cmd_line_shellfile:
  1737. try:
  1738. with open(self.cmd_line_shellfile, "r") as myfile:
  1739. cmd_line_shellfile_text = myfile.read()
  1740. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1741. except Exception as ext:
  1742. print("ERROR: ", ext)
  1743. sys.exit(2)
  1744. # ##########################
  1745. # ### Check for updates ####
  1746. # ##########################
  1747. # Separate thread (Not worker)
  1748. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1749. if (self.beta is False or self.beta is None) and \
  1750. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1751. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1752. self.thr2 = QtCore.QThread()
  1753. self.worker_task.emit({'fcn': self.version_check,
  1754. 'params': []})
  1755. self.thr2.start(QtCore.QThread.LowPriority)
  1756. # ###################################
  1757. # ### Variables for global usage ####
  1758. # ###################################
  1759. # coordinates for relative position display
  1760. self.rel_point1 = (0, 0)
  1761. self.rel_point2 = (0, 0)
  1762. # variable to store coordinates
  1763. self.pos = (0, 0)
  1764. self.pos_jump = (0, 0)
  1765. # decide if we have a double click or single click
  1766. self.doubleclick = False
  1767. # variable to store if a command is active (then the var is not None) and which one it is
  1768. self.command_active = None
  1769. # variable to store the status of moving selection action
  1770. # None value means that it's not an selection action
  1771. # True value = a selection from left to right
  1772. # False value = a selection from right to left
  1773. self.selection_type = None
  1774. # List to store the objects that are currently loaded in FlatCAM
  1775. # This list is updated on each object creation or object delete
  1776. self.all_objects_list = []
  1777. # List to store the objects that are selected
  1778. self.sel_objects_list = []
  1779. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1780. self.key_modifiers = None
  1781. # Variable to hold the status of the axis
  1782. self.toggle_axis = True
  1783. # Variable to store the status of the fullscreen event
  1784. self.toggle_fscreen = False
  1785. # Variable to store the status of the code editor
  1786. self.toggle_codeeditor = False
  1787. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1788. self.click_noproject = False
  1789. self.cursor = None
  1790. # Variable to store the GCODE that was edited
  1791. self.gcode_edited = ""
  1792. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1793. self.preferences_changed_flag = False
  1794. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1795. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1796. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1797. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1798. ]
  1799. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1800. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1801. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1802. 'mpf'
  1803. ]
  1804. self.svg_list = ['svg']
  1805. self.dxf_list = ['dxf']
  1806. self.pdf_list = ['pdf']
  1807. self.prj_list = ['flatprj']
  1808. self.conf_list = ['flatconfig']
  1809. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1810. # flag for polygons not cleared
  1811. self.poly_not_cleared = False
  1812. # VisPy visuals
  1813. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1814. self.isHovering = False
  1815. self.notHovering = True
  1816. # #########################################################
  1817. # ### Save defaults to factory_defaults.FlatConfig file ###
  1818. # ### It's done only once after install ###################
  1819. # #########################################################
  1820. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1821. fac_def_from_file = factory_file.read()
  1822. factory_defaults = json.loads(fac_def_from_file)
  1823. # if the file contain an empty dictionary then save the factory defaults into the file
  1824. if not factory_defaults:
  1825. self.save_factory_defaults(silent=False)
  1826. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1827. initial_lay = 'compact'
  1828. self.on_layout(lay=initial_lay)
  1829. # Set the combobox in Preferences to the current layout
  1830. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1831. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1832. factory_file.close()
  1833. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1834. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1835. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1836. ####################################################
  1837. # ### EDITOR section ###############################
  1838. ####################################################
  1839. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1840. # at the first launch of the App , the editors will not be functional.
  1841. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1842. self.exc_editor = FlatCAMExcEditor(self)
  1843. self.grb_editor = FlatCAMGrbEditor(self)
  1844. self.log.debug("Finished adding FlatCAM Editor's.")
  1845. # Post-GUI initialization: Experimental attempt
  1846. # to perform unit tests on the GUI.
  1847. # if post_gui is not None:
  1848. # post_gui(self)
  1849. App.log.debug("END of constructor. Releasing control.")
  1850. self.set_ui_title(name=_("New Project - Not saved"))
  1851. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1852. # the path/file_name must be enclosed in quotes if it contain spaces
  1853. if App.args:
  1854. self.args_at_startup.emit()
  1855. @staticmethod
  1856. def copy_and_overwrite(from_path, to_path):
  1857. """
  1858. From here:
  1859. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1860. :param from_path: source path
  1861. :param to_path: destination path
  1862. :return: None
  1863. """
  1864. if os.path.exists(to_path):
  1865. shutil.rmtree(to_path)
  1866. try:
  1867. shutil.copytree(from_path, to_path)
  1868. except FileNotFoundError:
  1869. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1870. shutil.copytree(from_new_path, to_path)
  1871. def on_startup_args(self):
  1872. log.debug("Application was started with an argument. Processing ...")
  1873. for argument in App.args:
  1874. if '.FlatPrj' in argument:
  1875. try:
  1876. project_name = str(argument)
  1877. if project_name == "":
  1878. self.inform.emit(_("Open cancelled."))
  1879. else:
  1880. # self.open_project(project_name)
  1881. run_from_arg = True
  1882. # self.worker_task.emit({'fcn': self.open_project,
  1883. # 'params': [project_name, run_from_arg]})
  1884. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1885. except Exception as e:
  1886. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1887. elif '.FlatConfig' in argument:
  1888. try:
  1889. file_name = str(argument)
  1890. if file_name == "":
  1891. self.inform.emit(_("Open Config file failed."))
  1892. else:
  1893. # run_from_arg = True
  1894. # self.worker_task.emit({'fcn': self.open_config_file,
  1895. # 'params': [file_name, run_from_arg]})
  1896. self.open_config_file(file_name, run_from_arg=True)
  1897. except Exception as e:
  1898. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1899. elif '.FlatScript' in argument:
  1900. try:
  1901. file_name = str(argument)
  1902. if file_name == "":
  1903. self.inform.emit(_("Open Script file failed."))
  1904. else:
  1905. # run_from_arg = True
  1906. # self.worker_task.emit({'fcn': self.open_script_file,
  1907. # 'params': [file_name, run_from_arg]})
  1908. self.on_filerunscript(name=file_name)
  1909. except Exception as e:
  1910. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1911. def set_ui_title(self, name):
  1912. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  1913. (self.version,
  1914. ('BETA' if self.beta else ''),
  1915. platform.architecture()[0],
  1916. name)
  1917. )
  1918. def defaults_read_form(self):
  1919. for option in self.defaults_form_fields:
  1920. try:
  1921. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1922. except Exception as e:
  1923. log.debug("App.defaults_read_form() --> %s" % str(e))
  1924. def defaults_write_form(self, factor=None, fl_units=None):
  1925. for option in self.defaults:
  1926. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  1927. # try:
  1928. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1929. # except KeyError:
  1930. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1931. # # TODO: Rethink this?
  1932. # pass
  1933. def defaults_write_form_field(self, field, factor=None, units=None):
  1934. try:
  1935. if factor is None:
  1936. if units is None:
  1937. self.defaults_form_fields[field].set_value(self.defaults[field])
  1938. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  1939. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  1940. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  1941. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  1942. else:
  1943. if units is None:
  1944. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1945. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  1946. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  1947. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  1948. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  1949. except KeyError:
  1950. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  1951. # TODO: Rethink this?
  1952. pass
  1953. except AttributeError:
  1954. log.debug(field)
  1955. def clear_pool(self):
  1956. self.pool.close()
  1957. self.pool = Pool()
  1958. self.pool_recreated.emit(self.pool)
  1959. gc.collect()
  1960. # the order that the tools are installed is important as they can depend on each other install position
  1961. def install_tools(self):
  1962. self.dblsidedtool = DblSidedTool(self)
  1963. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1964. self.measurement_tool = Measurement(self)
  1965. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1966. self.panelize_tool = Panelize(self)
  1967. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1968. self.film_tool = Film(self)
  1969. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1970. self.paste_tool = SolderPaste(self)
  1971. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  1972. self.calculator_tool = ToolCalculator(self)
  1973. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  1974. self.sub_tool = ToolSub(self)
  1975. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  1976. self.move_tool = ToolMove(self)
  1977. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1978. before=self.ui.menueditorigin)
  1979. self.cutout_tool = CutOut(self)
  1980. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1981. before=self.measurement_tool.menuAction)
  1982. self.ncclear_tool = NonCopperClear(self)
  1983. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1984. before=self.measurement_tool.menuAction, separator=True)
  1985. self.paint_tool = ToolPaint(self)
  1986. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1987. before=self.measurement_tool.menuAction, separator=True)
  1988. self.transform_tool = ToolTransform(self)
  1989. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1990. self.properties_tool = Properties(self)
  1991. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1992. self.pdf_tool = ToolPDF(self)
  1993. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  1994. separator=True)
  1995. self.image_tool = ToolImage(self)
  1996. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1997. separator=True)
  1998. self.pcb_wizard_tool = PcbWizard(self)
  1999. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2000. self.log.debug("Tools are installed.")
  2001. def remove_tools(self):
  2002. for act in self.ui.menutool.actions():
  2003. self.ui.menutool.removeAction(act)
  2004. def init_tools(self):
  2005. log.debug("init_tools()")
  2006. # delete the data currently in the Tools Tab and the Tab itself
  2007. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2008. if widget is not None:
  2009. widget.deleteLater()
  2010. self.ui.notebook.removeTab(2)
  2011. # rebuild the Tools Tab
  2012. self.ui.tool_tab = QtWidgets.QWidget()
  2013. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2014. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2015. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2016. self.ui.tool_scroll_area = VerticalScrollArea()
  2017. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2018. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2019. # first remove all of them
  2020. self.remove_tools()
  2021. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2022. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2023. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2024. # third install all of them
  2025. self.install_tools()
  2026. self.log.debug("Tools are initialized.")
  2027. # def parse_system_fonts(self):
  2028. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2029. # 'params': []})
  2030. def connect_toolbar_signals(self):
  2031. # Toolbar
  2032. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2033. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2034. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2035. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2036. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2037. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2038. self.ui.replot_btn.triggered.connect(self.plot_all)
  2039. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2040. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2041. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2042. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2043. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2044. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2045. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2046. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2047. self.ui.delete_btn.triggered.connect(self.on_delete)
  2048. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2049. # Tools Toolbar Signals
  2050. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2051. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2052. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2053. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2054. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2055. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2056. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2057. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2058. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2059. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2060. def object2editor(self):
  2061. """
  2062. Send the current Geometry or Excellon object (if any) into the editor.
  2063. :return: None
  2064. """
  2065. self.report_usage("object2editor()")
  2066. edited_object = self.collection.get_active()
  2067. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2068. isinstance(edited_object, FlatCAMExcellon):
  2069. pass
  2070. else:
  2071. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry, Gerber or Excellon Object to edit."))
  2072. return
  2073. if isinstance(edited_object, FlatCAMGeometry):
  2074. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2075. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2076. # we set the notebook to hidden
  2077. self.ui.splitter.setSizes([0, 1])
  2078. if edited_object.multigeo is True:
  2079. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2080. if len(edited_tools) > 1:
  2081. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2082. "is not possible.\n"
  2083. "Edit only one geometry at a time."))
  2084. # determine the tool dia of the selected tool
  2085. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2086. # now find the key in the edited_object.tools that has this tooldia
  2087. multi_tool = 1
  2088. for tool in edited_object.tools:
  2089. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2090. multi_tool = tool
  2091. break
  2092. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2093. else:
  2094. self.geo_editor.edit_fcgeometry(edited_object)
  2095. # set call source to the Editor we go into
  2096. self.call_source = 'geo_editor'
  2097. elif isinstance(edited_object, FlatCAMExcellon):
  2098. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2099. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2100. if self.ui.splitter.sizes()[0] == 0:
  2101. self.ui.splitter.setSizes([1, 1])
  2102. self.exc_editor.edit_fcexcellon(edited_object)
  2103. # set call source to the Editor we go into
  2104. self.call_source = 'exc_editor'
  2105. elif isinstance(edited_object, FlatCAMGerber):
  2106. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2107. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2108. if self.ui.splitter.sizes()[0] == 0:
  2109. self.ui.splitter.setSizes([1, 1])
  2110. self.grb_editor.edit_fcgerber(edited_object)
  2111. # set call source to the Editor we go into
  2112. self.call_source = 'grb_editor'
  2113. # make sure that we can't select another object while in Editor Mode:
  2114. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2115. self.ui.project_frame.setDisabled(True)
  2116. # delete any selection shape that might be active as they are not relevant in Editor
  2117. self.delete_selection_shape()
  2118. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2119. self.ui.plot_tab_area.protectTab(0)
  2120. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  2121. self.should_we_save = True
  2122. def editor2object(self, cleanup=None):
  2123. """
  2124. Transfers the Geometry or Excellon from the editor to the current object.
  2125. :return: None
  2126. """
  2127. self.report_usage("editor2object()")
  2128. # do not update a geometry or excellon object unless it comes out of an editor
  2129. if self.call_source != 'app':
  2130. edited_obj = self.collection.get_active()
  2131. if cleanup is None:
  2132. msgbox = QtWidgets.QMessageBox()
  2133. msgbox.setText(_("Do you want to save the edited object?"))
  2134. msgbox.setWindowTitle(_("Close Editor"))
  2135. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2136. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2137. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2138. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2139. msgbox.setDefaultButton(bt_yes)
  2140. msgbox.exec_()
  2141. response = msgbox.clickedButton()
  2142. if response == bt_yes:
  2143. # clean the Tools Tab
  2144. self.ui.tool_scroll_area.takeWidget()
  2145. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2146. self.ui.notebook.setTabText(2, "Tool")
  2147. if isinstance(edited_obj, FlatCAMGeometry):
  2148. obj_type = "Geometry"
  2149. if cleanup is None:
  2150. self.geo_editor.update_fcgeometry(edited_obj)
  2151. self.geo_editor.update_options(edited_obj)
  2152. self.geo_editor.deactivate()
  2153. # update the geo object options so it is including the bounding box values
  2154. try:
  2155. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2156. edited_obj.options['xmin'] = xmin
  2157. edited_obj.options['ymin'] = ymin
  2158. edited_obj.options['xmax'] = xmax
  2159. edited_obj.options['ymax'] = ymax
  2160. except AttributeError as e:
  2161. self.inform.emit(_("[WARNING] Object empty after edit."))
  2162. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2163. elif isinstance(edited_obj, FlatCAMGerber):
  2164. obj_type = "Gerber"
  2165. if cleanup is None:
  2166. self.grb_editor.update_fcgerber()
  2167. self.grb_editor.update_options(edited_obj)
  2168. self.grb_editor.deactivate_grb_editor()
  2169. # delete the old object (the source object) if it was an empty one
  2170. if len(edited_obj.solid_geometry) == 0:
  2171. old_name = edited_obj.options['name']
  2172. self.collection.set_active(old_name)
  2173. self.collection.delete_active()
  2174. elif isinstance(edited_obj, FlatCAMExcellon):
  2175. obj_type = "Excellon"
  2176. if cleanup is None:
  2177. self.exc_editor.update_fcexcellon(edited_obj)
  2178. self.exc_editor.update_options(edited_obj)
  2179. self.exc_editor.deactivate()
  2180. else:
  2181. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2182. return
  2183. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  2184. elif response == bt_no:
  2185. # clean the Tools Tab
  2186. self.ui.tool_scroll_area.takeWidget()
  2187. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2188. self.ui.notebook.setTabText(2, "Tool")
  2189. if isinstance(edited_obj, FlatCAMGeometry):
  2190. self.geo_editor.deactivate()
  2191. elif isinstance(edited_obj, FlatCAMGerber):
  2192. self.grb_editor.deactivate_grb_editor()
  2193. elif isinstance(edited_obj, FlatCAMExcellon):
  2194. self.exc_editor.deactivate()
  2195. # set focus on the project tab
  2196. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2197. else:
  2198. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2199. return
  2200. elif response == bt_cancel:
  2201. return
  2202. else:
  2203. if isinstance(edited_obj, FlatCAMGeometry):
  2204. self.geo_editor.deactivate()
  2205. elif isinstance(edited_obj, FlatCAMGerber):
  2206. self.grb_editor.deactivate_grb_editor()
  2207. elif isinstance(edited_obj, FlatCAMExcellon):
  2208. self.exc_editor.deactivate()
  2209. else:
  2210. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  2211. return
  2212. # if notebook is hidden we show it
  2213. if self.ui.splitter.sizes()[0] == 0:
  2214. self.ui.splitter.setSizes([1, 1])
  2215. # restore the call_source to app
  2216. self.call_source = 'app'
  2217. edited_obj.plot()
  2218. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2219. self.ui.plot_tab_area.protectTab(0)
  2220. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2221. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2222. self.ui.project_frame.setDisabled(False)
  2223. def get_last_folder(self):
  2224. return self.defaults["global_last_folder"]
  2225. def get_last_save_folder(self):
  2226. loc = self.defaults["global_last_save_folder"]
  2227. if loc is None:
  2228. loc = self.defaults["global_last_folder"]
  2229. if loc is None:
  2230. loc = os.path.dirname(__file__)
  2231. return loc
  2232. def report_usage(self, resource):
  2233. """
  2234. Increments usage counter for the given resource
  2235. in self.defaults['global_stats'].
  2236. :param resource: Name of the resource.
  2237. :return: None
  2238. """
  2239. if resource in self.defaults['global_stats']:
  2240. self.defaults['global_stats'][resource] += 1
  2241. else:
  2242. self.defaults['global_stats'][resource] = 1
  2243. def init_tcl(self):
  2244. if hasattr(self, 'tcl'):
  2245. # self.tcl = None
  2246. # TODO we need to clean non default variables and procedures here
  2247. # new object cannot be used here as it will not remember values created for next passes,
  2248. # because tcl was execudted in old instance of TCL
  2249. pass
  2250. else:
  2251. self.tcl = tk.Tcl()
  2252. self.setup_shell()
  2253. self.log.debug("TCL Shell has been initialized.")
  2254. # TODO: This shouldn't be here.
  2255. class TclErrorException(Exception):
  2256. """
  2257. this exception is defined here, to be able catch it if we ssuccessfully handle all errors from shell command
  2258. """
  2259. pass
  2260. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2261. """
  2262. Shows a message on the FlatCAM Shell
  2263. :param msg: Message to display.
  2264. :param show: Opens the shell.
  2265. :param error: Shows the message as an error.
  2266. :param warning: Shows the message as an warning.
  2267. :param success: Shows the message as an success.
  2268. :param selected: Indicate that something was selected on canvas
  2269. :return: None
  2270. """
  2271. if show:
  2272. self.ui.shell_dock.show()
  2273. try:
  2274. if error:
  2275. self.shell.append_error(msg + "\n")
  2276. elif warning:
  2277. self.shell.append_warning(msg + "\n")
  2278. elif success:
  2279. self.shell.append_success(msg + "\n")
  2280. elif selected:
  2281. self.shell.append_selected(msg + "\n")
  2282. else:
  2283. self.shell.append_output(msg + "\n")
  2284. except AttributeError:
  2285. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2286. def raise_tcl_unknown_error(self, unknownException):
  2287. """
  2288. Raise exception if is different type than TclErrorException
  2289. this is here mainly to show unknown errors inside TCL shell console.
  2290. :param unknownException:
  2291. :return:
  2292. """
  2293. if not isinstance(unknownException, self.TclErrorException):
  2294. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2295. else:
  2296. raise unknownException
  2297. def display_tcl_error(self, error, error_info=None):
  2298. """
  2299. Escape bracket [ with '\' otherwise there is error
  2300. "ERROR: missing close-bracket" instead of real error
  2301. :param error: it may be text or exception
  2302. :param error_info: Some informations about the error
  2303. :return: None
  2304. """
  2305. if isinstance(error, Exception):
  2306. exc_type, exc_value, exc_traceback = error_info
  2307. if not isinstance(error, self.TclErrorException):
  2308. show_trace = 1
  2309. else:
  2310. show_trace = int(self.defaults['global_verbose_error_level'])
  2311. if show_trace > 0:
  2312. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2313. trc_formated = []
  2314. for a in reversed(trc):
  2315. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2316. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2317. else:
  2318. text = "%s" % error
  2319. else:
  2320. text = error
  2321. text = text.replace('[', '\\[').replace('"', '\\"')
  2322. self.tcl.eval('return -code error "%s"' % text)
  2323. def raise_tcl_error(self, text):
  2324. """
  2325. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2326. :param text: text of error
  2327. :return: raise exception
  2328. """
  2329. self.display_tcl_error(text)
  2330. raise self.TclErrorException(text)
  2331. def exec_command(self, text):
  2332. """
  2333. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2334. Also handles execution in separated threads
  2335. :param text:
  2336. :return: output if there was any
  2337. """
  2338. self.report_usage('exec_command')
  2339. result = self.exec_command_test(text, False)
  2340. # MS: added this method call so the geometry is updated once the TCL command is executed
  2341. self.plot_all()
  2342. return result
  2343. def exec_command_test(self, text, reraise=True):
  2344. """
  2345. Same as exec_command(...) with additional control over exceptions.
  2346. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2347. :param text: Input command
  2348. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2349. :return: Output from the command
  2350. """
  2351. text = str(text)
  2352. try:
  2353. self.shell.open_proccessing() # Disables input box.
  2354. result = self.tcl.eval(str(text))
  2355. if result != 'None':
  2356. self.shell.append_output(result + '\n')
  2357. except tk.TclError as e:
  2358. # This will display more precise answer if something in TCL shell fails
  2359. result = self.tcl.eval("set errorInfo")
  2360. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2361. self.shell.append_error('ERROR: ' + result + '\n')
  2362. # Show error in console and just return or in test raise exception
  2363. if reraise:
  2364. raise e
  2365. finally:
  2366. self.shell.close_proccessing()
  2367. pass
  2368. return result
  2369. # """
  2370. # Code below is unsused. Saved for later.
  2371. # """
  2372. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2373. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2374. # self.log.debug(parts)
  2375. # try:
  2376. # if parts[0] not in commands:
  2377. # self.shell.append_error("Unknown command\n")
  2378. # return
  2379. #
  2380. # #import inspect
  2381. # #inspect.getargspec(someMethod)
  2382. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2383. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2384. # self.shell.append_error(
  2385. # "Command %s takes %d arguments. %d given.\n" %
  2386. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2387. # )
  2388. # return
  2389. #
  2390. # cmdfcn = commands[parts[0]]["fcn"]
  2391. # cmdconv = commands[parts[0]]["converters"]
  2392. # if len(parts) - 1 > 0:
  2393. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2394. # else:
  2395. # retval = cmdfcn()
  2396. # retfcn = commands[parts[0]]["retfcn"]
  2397. # if retval and retfcn(retval):
  2398. # self.shell.append_output(retfcn(retval) + "\n")
  2399. #
  2400. # except Exception as e:
  2401. # #self.shell.append_error(''.join(traceback.format_exc()))
  2402. # #self.shell.append_error("?\n")
  2403. # self.shell.append_error(str(e) + "\n")
  2404. def info(self, msg):
  2405. """
  2406. Informs the user. Normally on the status bar, optionally
  2407. also on the shell.
  2408. :param msg: Text to write.
  2409. :return: None
  2410. """
  2411. # Type of message in brackets at the beginning of the message.
  2412. match = re.search("\[([^\]]+)\](.*)", msg)
  2413. if match:
  2414. level = match.group(1)
  2415. msg_ = match.group(2)
  2416. self.ui.fcinfo.set_status(str(msg_), level=level)
  2417. if level.lower() == "error":
  2418. self.shell_message(msg, error=True, show=True)
  2419. elif level.lower() == "warning":
  2420. self.shell_message(msg, warning=True, show=True)
  2421. elif level.lower() == "error_notcl":
  2422. self.shell_message(msg, error=True, show=False)
  2423. elif level.lower() == "warning_notcl":
  2424. self.shell_message(msg, warning=True, show=False)
  2425. elif level.lower() == "success":
  2426. self.shell_message(msg, success=True, show=False)
  2427. elif level.lower() == "selected":
  2428. self.shell_message(msg, selected=True, show=False)
  2429. else:
  2430. self.shell_message(msg, show=False)
  2431. else:
  2432. self.ui.fcinfo.set_status(str(msg), level="info")
  2433. # make sure that if the message is to clear the infobar with a space
  2434. # is not printed over and over on the shell
  2435. if msg != '':
  2436. self.shell_message(msg)
  2437. def restore_toolbar_view(self):
  2438. tb = self.defaults["global_toolbar_view"]
  2439. if tb & 1:
  2440. self.ui.toolbarfile.setVisible(True)
  2441. else:
  2442. self.ui.toolbarfile.setVisible(False)
  2443. if tb & 2:
  2444. self.ui.toolbargeo.setVisible(True)
  2445. else:
  2446. self.ui.toolbargeo.setVisible(False)
  2447. if tb & 4:
  2448. self.ui.toolbarview.setVisible(True)
  2449. else:
  2450. self.ui.toolbarview.setVisible(False)
  2451. if tb & 8:
  2452. self.ui.toolbartools.setVisible(True)
  2453. else:
  2454. self.ui.toolbartools.setVisible(False)
  2455. if tb & 16:
  2456. self.ui.exc_edit_toolbar.setVisible(True)
  2457. else:
  2458. self.ui.exc_edit_toolbar.setVisible(False)
  2459. if tb & 32:
  2460. self.ui.geo_edit_toolbar.setVisible(True)
  2461. else:
  2462. self.ui.geo_edit_toolbar.setVisible(False)
  2463. if tb & 64:
  2464. self.ui.grb_edit_toolbar.setVisible(True)
  2465. else:
  2466. self.ui.grb_edit_toolbar.setVisible(False)
  2467. if tb & 128:
  2468. self.ui.snap_toolbar.setVisible(True)
  2469. else:
  2470. self.ui.snap_toolbar.setVisible(False)
  2471. if tb & 256:
  2472. self.ui.toolbarshell.setVisible(True)
  2473. else:
  2474. self.ui.toolbarshell.setVisible(False)
  2475. def load_defaults(self, filename):
  2476. """
  2477. Loads the aplication's default settings from current_defaults.FlatConfig into
  2478. ``self.defaults``.
  2479. :return: None
  2480. """
  2481. try:
  2482. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2483. options = f.read()
  2484. f.close()
  2485. except IOError:
  2486. self.log.error("Could not load defaults file.")
  2487. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2488. # in case the defaults file can't be loaded, show all toolbars
  2489. self.defaults["global_toolbar_view"] = 511
  2490. return
  2491. try:
  2492. defaults = json.loads(options)
  2493. except:
  2494. # in case the defaults file can't be loaded, show all toolbars
  2495. self.defaults["global_toolbar_view"] = 511
  2496. e = sys.exc_info()[0]
  2497. App.log.error(str(e))
  2498. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2499. return
  2500. self.defaults.update(defaults)
  2501. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2502. # restore the toolbar view
  2503. self.restore_toolbar_view()
  2504. def on_import_preferences(self):
  2505. """
  2506. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2507. ``self.defaults``.
  2508. :return: None
  2509. """
  2510. self.report_usage("on_import_preferences")
  2511. App.log.debug("on_import_preferences()")
  2512. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2513. try:
  2514. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2515. directory=self.data_path,
  2516. filter=filter_)
  2517. except TypeError:
  2518. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2519. filter=filter_)
  2520. filename = str(filename)
  2521. if filename == "":
  2522. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2523. else:
  2524. try:
  2525. f = open(filename)
  2526. options = f.read()
  2527. f.close()
  2528. except IOError:
  2529. self.log.error("Could not load defaults file.")
  2530. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2531. return
  2532. try:
  2533. defaults_from_file = json.loads(options)
  2534. except Exception as e:
  2535. e = sys.exc_info()[0]
  2536. App.log.error(str(e))
  2537. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2538. return
  2539. self.defaults.update(defaults_from_file)
  2540. self.on_preferences_edited()
  2541. self.inform.emit(_("[success] Imported Defaults from %s") % filename)
  2542. def on_export_preferences(self):
  2543. self.report_usage("on_export_preferences")
  2544. App.log.debug("on_export_preferences()")
  2545. defaults_file_content = None
  2546. self.date = str(datetime.today()).rpartition('.')[0]
  2547. self.date = ''.join(c for c in self.date if c not in ':-')
  2548. self.date = self.date.replace(' ', '_')
  2549. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2550. try:
  2551. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2552. caption=_("Export FlatCAM Preferences"),
  2553. directory=self.data_path + '/preferences_' + self.date,
  2554. filter=filter__
  2555. )
  2556. except TypeError:
  2557. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2558. filter=filter__)
  2559. filename = str(filename)
  2560. defaults_from_file = {}
  2561. if filename == "":
  2562. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2563. return
  2564. else:
  2565. try:
  2566. f = open(filename, 'w')
  2567. defaults_file_content = f.read()
  2568. f.close()
  2569. except PermissionError:
  2570. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  2571. "Most likely another app is holding the file open and not accessible."))
  2572. return
  2573. except IOError:
  2574. App.log.debug('Creating a new preferences file ...')
  2575. f = open(filename, 'w')
  2576. json.dump({}, f)
  2577. f.close()
  2578. except:
  2579. e = sys.exc_info()[0]
  2580. App.log.error("Could not load defaults file.")
  2581. App.log.error(str(e))
  2582. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2583. return
  2584. try:
  2585. defaults_from_file = json.loads(defaults_file_content)
  2586. except:
  2587. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2588. # Update options
  2589. self.defaults_read_form()
  2590. defaults_from_file.update(self.defaults)
  2591. self.propagate_defaults(silent=True)
  2592. # Save update options
  2593. try:
  2594. f = open(filename, "w")
  2595. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2596. f.close()
  2597. except:
  2598. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2599. return
  2600. if self.defaults["global_open_style"] is False:
  2601. self.file_opened.emit("preferences", filename)
  2602. self.file_saved.emit("preferences", filename)
  2603. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2604. def on_preferences_open_folder(self):
  2605. self.report_usage("on_preferences_open_folder()")
  2606. if sys.platform == 'win32':
  2607. subprocess.Popen('explorer %s' % self.data_path)
  2608. elif sys.platform == 'darwin':
  2609. os.system('open "%s"' % self.data_path)
  2610. else:
  2611. subprocess.Popen(['xdg-open', self.data_path])
  2612. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2613. def save_geometry(self, x, y, width, height, notebook_width):
  2614. self.defaults["global_def_win_x"] = x
  2615. self.defaults["global_def_win_y"] = y
  2616. self.defaults["global_def_win_w"] = width
  2617. self.defaults["global_def_win_h"] = height
  2618. self.defaults["global_def_notebook_width"] = notebook_width
  2619. self.save_defaults()
  2620. def message_dialog(self, title, message, kind="info"):
  2621. icon = {"info": QtWidgets.QMessageBox.Information,
  2622. "warning": QtWidgets.QMessageBox.Warning,
  2623. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2624. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2625. dlg.setText(message)
  2626. dlg.exec_()
  2627. def register_recent(self, kind, filename):
  2628. self.log.debug("register_recent()")
  2629. self.log.debug(" %s" % kind)
  2630. self.log.debug(" %s" % filename)
  2631. record = {'kind': str(kind), 'filename': str(filename)}
  2632. if record in self.recent:
  2633. return
  2634. if record in self.recent_projects:
  2635. return
  2636. if record['kind'] == 'project':
  2637. self.recent_projects.insert(0, record)
  2638. else:
  2639. self.recent.insert(0, record)
  2640. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2641. self.recent.pop()
  2642. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2643. self.recent_projects.pop()
  2644. try:
  2645. f = open(self.data_path + '/recent.json', 'w')
  2646. except IOError:
  2647. App.log.error("Failed to open recent items file for writing.")
  2648. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2649. return
  2650. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2651. f.close()
  2652. try:
  2653. fp = open(self.data_path + '/recent_projects.json', 'w')
  2654. except IOError:
  2655. App.log.error("Failed to open recent items file for writing.")
  2656. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent projects file for writing.'))
  2657. return
  2658. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2659. fp.close()
  2660. # Re-build the recent items menu
  2661. self.setup_recent_items()
  2662. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2663. """
  2664. Creates a new specialized FlatCAMObj and attaches it to the application,
  2665. this is, updates the GUI accordingly, any other records and plots it.
  2666. This method is thread-safe.
  2667. Notes:
  2668. * If the name is in use, the self.collection will modify it
  2669. when appending it to the collection. There is no need to handle
  2670. name conflicts here.
  2671. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2672. :type kind: str
  2673. :param name: Name for the object.
  2674. :type name: str
  2675. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2676. The function is called with 2 parameters: the new object and the App instance.
  2677. :type initialize: function
  2678. :param active:
  2679. :param fit:
  2680. :param plot: If to plot the resulting object
  2681. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2682. self.colleaction
  2683. :return: None
  2684. :rtype: None
  2685. """
  2686. App.log.debug("new_object()")
  2687. obj_plot = plot
  2688. obj_autoselected = autoselected
  2689. t0 = time.time() # Debug
  2690. # ## Create object
  2691. classdict = {
  2692. "gerber": FlatCAMGerber,
  2693. "excellon": FlatCAMExcellon,
  2694. "cncjob": FlatCAMCNCjob,
  2695. "geometry": FlatCAMGeometry
  2696. }
  2697. App.log.debug("Calling object constructor...")
  2698. obj = classdict[kind](name)
  2699. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2700. # Set options from "Project options" form
  2701. self.options_read_form()
  2702. # IMPORTANT
  2703. # The key names in defaults and options dictionary's are not random:
  2704. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2705. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2706. # the options from project options form into the self.options. After that, below, depending on the type of
  2707. # object that is created, it will strip the name of the object and the underline (if the original key was
  2708. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2709. # "toolchange"
  2710. for option in self.options:
  2711. if option.find(kind + "_") == 0:
  2712. oname = option[len(kind) + 1:]
  2713. obj.options[oname] = self.options[option]
  2714. obj.isHovering = False
  2715. obj.notHovering = True
  2716. # Initialize as per user request
  2717. # User must take care to implement initialize
  2718. # in a thread-safe way as is is likely that we
  2719. # have been invoked in a separate thread.
  2720. t1 = time.time()
  2721. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2722. try:
  2723. return_value = initialize(obj, self)
  2724. except Exception as e:
  2725. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2726. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2727. msg += traceback.format_exc()
  2728. self.inform.emit(msg)
  2729. # if str(e) == "Empty Geometry":
  2730. # self.inform.emit("[ERROR_NOTCL] )
  2731. # else:
  2732. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2733. return "fail"
  2734. t2 = time.time()
  2735. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2736. if return_value == 'fail':
  2737. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2738. return "fail"
  2739. # Check units and convert if necessary
  2740. # This condition CAN be true because initialize() can change obj.units
  2741. if self.options["units"].upper() != obj.units.upper():
  2742. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2743. obj.convert_units(self.options["units"])
  2744. t3 = time.time()
  2745. self.log.debug("%f seconds converting units." % (t3 - t2))
  2746. # Create the bounding box for the object and then add the results to the obj.options
  2747. try:
  2748. xmin, ymin, xmax, ymax = obj.bounds()
  2749. obj.options['xmin'] = xmin
  2750. obj.options['ymin'] = ymin
  2751. obj.options['xmax'] = xmax
  2752. obj.options['ymax'] = ymax
  2753. except Exception as e:
  2754. log.warning("The object has no bounds properties. %s" % str(e))
  2755. return "fail"
  2756. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2757. # Move the object to the main thread and let the app know that it is available.
  2758. obj.moveToThread(self.main_thread)
  2759. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2760. return obj
  2761. def new_excellon_object(self):
  2762. self.report_usage("new_excellon_object()")
  2763. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2764. def new_geometry_object(self):
  2765. self.report_usage("new_geometry_object()")
  2766. def initialize(obj, self):
  2767. obj.multitool = False
  2768. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2769. def new_gerber_object(self):
  2770. self.report_usage("new_gerber_object()")
  2771. def initialize(grb_obj, self):
  2772. grb_obj.multitool = False
  2773. grb_obj.source_file = []
  2774. grb_obj.multigeo = False
  2775. grb_obj.follow = False
  2776. grb_obj.apertures = {}
  2777. grb_obj.solid_geometry = []
  2778. try:
  2779. grb_obj.options['xmin'] = 0
  2780. grb_obj.options['ymin'] = 0
  2781. grb_obj.options['xmax'] = 0
  2782. grb_obj.options['ymax'] = 0
  2783. except KeyError:
  2784. pass
  2785. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2786. def on_object_created(self, obj, plot, autoselect):
  2787. """
  2788. Event callback for object creation.
  2789. :param obj: The newly created FlatCAM object.
  2790. :return: None
  2791. """
  2792. t0 = time.time() # DEBUG
  2793. self.log.debug("on_object_created()")
  2794. # The Collection might change the name if there is a collision
  2795. self.collection.append(obj)
  2796. # after adding the object to the collection always update the list of objects that are in the collection
  2797. self.all_objects_list = self.collection.get_list()
  2798. # self.inform.emit('[selected] %s created & selected: %s' %
  2799. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2800. if obj.kind == 'gerber':
  2801. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2802. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2803. elif obj.kind == 'excellon':
  2804. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2805. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2806. elif obj.kind == 'cncjob':
  2807. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2808. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2809. elif obj.kind == 'geometry':
  2810. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2811. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2812. # update the SHELL auto-completer model with the name of the new object
  2813. self.myKeywords.append(obj.options['name'])
  2814. self.shell._edit.set_model_data(self.myKeywords)
  2815. self.ui.code_editor.set_model_data(self.myKeywords)
  2816. if autoselect:
  2817. # select the just opened object but deselect the previous ones
  2818. self.collection.set_all_inactive()
  2819. self.collection.set_active(obj.options["name"])
  2820. else:
  2821. self.collection.set_all_inactive()
  2822. # here it is done the object plotting
  2823. def worker_task(t_obj):
  2824. with self.proc_container.new("Plotting"):
  2825. if isinstance(t_obj, FlatCAMCNCjob):
  2826. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2827. else:
  2828. t_obj.plot()
  2829. t1 = time.time() # DEBUG
  2830. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2831. self.object_plotted.emit(t_obj)
  2832. # Send to worker
  2833. # self.worker.add_task(worker_task, [self])
  2834. if plot is True:
  2835. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2836. def on_object_changed(self, obj):
  2837. # update the bounding box data from obj.options
  2838. xmin, ymin, xmax, ymax = obj.bounds()
  2839. obj.options['xmin'] = xmin
  2840. obj.options['ymin'] = ymin
  2841. obj.options['xmax'] = xmax
  2842. obj.options['ymax'] = ymax
  2843. log.debug("Object changed, updating the bounding box data on self.options")
  2844. # delete the old selection shape
  2845. self.delete_selection_shape()
  2846. self.should_we_save = True
  2847. def on_object_plotted(self, obj):
  2848. self.on_zoom_fit(None)
  2849. def options_read_form(self):
  2850. for option in self.options_form_fields:
  2851. self.options[option] = self.options_form_fields[option].get_value()
  2852. def options_write_form(self):
  2853. for option in self.options:
  2854. self.options_write_form_field(option)
  2855. def options_write_form_field(self, field):
  2856. try:
  2857. self.options_form_fields[field].set_value(self.options[field])
  2858. except KeyError:
  2859. # Changed from error to debug. This allows to have data stored
  2860. # which is not user-editable.
  2861. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2862. pass
  2863. def on_about(self):
  2864. """
  2865. Displays the "about" dialog.
  2866. :return: None
  2867. """
  2868. self.report_usage("on_about")
  2869. version = self.version
  2870. version_date = self.version_date
  2871. beta = self.beta
  2872. class AboutDialog(QtWidgets.QDialog):
  2873. def __init__(self, parent=None):
  2874. QtWidgets.QDialog.__init__(self, parent)
  2875. # Icon and title
  2876. self.setWindowIcon(parent.app_icon)
  2877. self.setWindowTitle("FlatCAM")
  2878. layout1 = QtWidgets.QVBoxLayout()
  2879. self.setLayout(layout1)
  2880. layout2 = QtWidgets.QHBoxLayout()
  2881. layout1.addLayout(layout2)
  2882. logo = QtWidgets.QLabel()
  2883. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2884. layout2.addWidget(logo, stretch=0)
  2885. title = QtWidgets.QLabel(
  2886. _(
  2887. "<font size=8><B>FlatCAM</B></font><BR>"
  2888. "Version {version} {beta} ({date}) - {arch} <BR>"
  2889. "<BR>"
  2890. "2D Computer-Aided Printed Circuit Board<BR>"
  2891. "Manufacturing.<BR>"
  2892. "<BR>"
  2893. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2894. "<BR>"
  2895. "<B> Main Contributors:</B><BR>"
  2896. "Denis Hayrullin<BR>"
  2897. "Kamil Sopko<BR>"
  2898. "Marius Stanciu<BR>"
  2899. "Matthieu Berthomé<BR>"
  2900. "and many others found "
  2901. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2902. "<BR>"
  2903. "Development is done "
  2904. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2905. "DOWNLOAD area "
  2906. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2907. ""
  2908. ).format(version=version,
  2909. beta=('BETA' if beta else ''),
  2910. date=version_date,
  2911. arch=platform.architecture()[0])
  2912. )
  2913. title.setOpenExternalLinks(True)
  2914. layout2.addWidget(title, stretch=1)
  2915. layout3 = QtWidgets.QHBoxLayout()
  2916. layout1.addLayout(layout3)
  2917. layout3.addStretch()
  2918. okbtn = QtWidgets.QPushButton(_("Close"))
  2919. layout3.addWidget(okbtn)
  2920. okbtn.clicked.connect(self.accept)
  2921. AboutDialog(self.ui).exec_()
  2922. def on_file_savedefaults(self):
  2923. """
  2924. Callback for menu item File->Save Defaults. Saves application default options
  2925. ``self.defaults`` to current_defaults.FlatConfig.
  2926. :return: None
  2927. """
  2928. self.save_defaults()
  2929. # def on_app_exit(self):
  2930. # self.report_usage("on_app_exit()")
  2931. #
  2932. # if self.collection.get_list():
  2933. # msgbox = QtWidgets.QMessageBox()
  2934. # # msgbox.setText("<B>Save changes ...</B>")
  2935. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2936. # "\n"
  2937. # "Do you want to Save the project?")
  2938. # msgbox.setWindowTitle("Save changes")
  2939. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2940. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2941. # QtWidgets.QMessageBox.Cancel)
  2942. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2943. #
  2944. # response = msgbox.exec_()
  2945. #
  2946. # if response == QtWidgets.QMessageBox.Yes:
  2947. # self.on_file_saveprojectas(thread=False)
  2948. # elif response == QtWidgets.QMessageBox.Cancel:
  2949. # return
  2950. # self.save_defaults()
  2951. # else:
  2952. # self.save_defaults()
  2953. # log.debug("Application defaults saved ... Exit event.")
  2954. # QtWidgets.qApp.quit()
  2955. def save_defaults(self, silent=False):
  2956. """
  2957. Saves application default options
  2958. ``self.defaults`` to current_defaults.FlatConfig.
  2959. :return: None
  2960. """
  2961. self.report_usage("save_defaults")
  2962. # Read options from file
  2963. try:
  2964. f = open(self.data_path + "/current_defaults.FlatConfig")
  2965. defaults_file_content = f.read()
  2966. f.close()
  2967. except:
  2968. e = sys.exc_info()[0]
  2969. App.log.error("Could not load defaults file.")
  2970. App.log.error(str(e))
  2971. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2972. return
  2973. try:
  2974. defaults = json.loads(defaults_file_content)
  2975. except:
  2976. e = sys.exc_info()[0]
  2977. App.log.error("Failed to parse defaults file.")
  2978. App.log.error(str(e))
  2979. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2980. return
  2981. # Update options
  2982. self.defaults_read_form()
  2983. defaults.update(self.defaults)
  2984. self.propagate_defaults(silent=True)
  2985. # Save the toolbar view
  2986. tb_status = 0
  2987. if self.ui.toolbarfile.isVisible():
  2988. tb_status += 1
  2989. if self.ui.toolbargeo.isVisible():
  2990. tb_status += 2
  2991. if self.ui.toolbarview.isVisible():
  2992. tb_status += 4
  2993. if self.ui.toolbartools.isVisible():
  2994. tb_status += 8
  2995. if self.ui.exc_edit_toolbar.isVisible():
  2996. tb_status += 16
  2997. if self.ui.geo_edit_toolbar.isVisible():
  2998. tb_status += 32
  2999. if self.ui.grb_edit_toolbar.isVisible():
  3000. tb_status += 64
  3001. if self.ui.snap_toolbar.isVisible():
  3002. tb_status += 128
  3003. if self.ui.toolbarshell.isVisible():
  3004. tb_status += 256
  3005. self.defaults["global_toolbar_view"] = tb_status
  3006. # Save update options
  3007. try:
  3008. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  3009. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3010. f.close()
  3011. except:
  3012. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  3013. return
  3014. if not silent:
  3015. self.inform.emit(_("[success] Defaults saved."))
  3016. def save_factory_defaults(self, silent=False):
  3017. """
  3018. Saves application factory default options
  3019. ``self.defaults`` to factory_defaults.FlatConfig.
  3020. It's a one time job done just after the first install.
  3021. :return: None
  3022. """
  3023. self.report_usage("save_factory_defaults")
  3024. # Read options from file
  3025. try:
  3026. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  3027. factory_defaults_file_content = f_f_def.read()
  3028. f_f_def.close()
  3029. except:
  3030. e = sys.exc_info()[0]
  3031. App.log.error("Could not load factory defaults file.")
  3032. App.log.error(str(e))
  3033. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  3034. return
  3035. try:
  3036. factory_defaults = json.loads(factory_defaults_file_content)
  3037. except:
  3038. e = sys.exc_info()[0]
  3039. App.log.error("Failed to parse factory defaults file.")
  3040. App.log.error(str(e))
  3041. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  3042. return
  3043. # Update options
  3044. self.defaults_read_form()
  3045. factory_defaults.update(self.defaults)
  3046. self.propagate_defaults(silent=True)
  3047. # Save update options
  3048. try:
  3049. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3050. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3051. f_f_def_s.close()
  3052. except:
  3053. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  3054. return
  3055. if silent is False:
  3056. self.inform.emit(_("Factory defaults saved."))
  3057. def final_save(self):
  3058. if self.save_in_progress:
  3059. self.inform.emit(_("[WARNING_NOTCL] Application is saving the project. Please wait ..."))
  3060. return
  3061. if self.should_we_save and self.collection.get_list():
  3062. msgbox = QtWidgets.QMessageBox()
  3063. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3064. "\n"
  3065. "Do you want to Save the project?"))
  3066. msgbox.setWindowTitle(_("Save changes"))
  3067. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3068. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3069. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3070. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3071. msgbox.setDefaultButton(bt_yes)
  3072. msgbox.exec_()
  3073. response = msgbox.clickedButton()
  3074. if response == bt_yes:
  3075. self.on_file_saveprojectas(thread=True, quit=True)
  3076. elif response == bt_no:
  3077. self.quit_application()
  3078. elif response == bt_cancel:
  3079. return
  3080. else:
  3081. self.quit_application()
  3082. def quit_application(self):
  3083. self.save_defaults()
  3084. log.debug("App.final_save() --> App Defaults saved.")
  3085. # save toolbar state to file
  3086. settings = QSettings("Open Source", "FlatCAM")
  3087. settings.setValue('saved_gui_state', self.ui.saveState())
  3088. settings.setValue('maximized_gui', self.ui.isMaximized())
  3089. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3090. settings.setValue('notebook_font_size',
  3091. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3092. settings.setValue('axis_font_size',
  3093. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3094. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3095. # This will write the setting to the platform specific storage.
  3096. del settings
  3097. log.debug("App.final_save() --> App UI state saved.")
  3098. QtWidgets.qApp.quit()
  3099. def on_toggle_shell(self):
  3100. """
  3101. toggle shell if is visible close it if closed open it
  3102. :return:
  3103. """
  3104. self.report_usage("on_toggle_shell()")
  3105. if self.ui.shell_dock.isVisible():
  3106. self.ui.shell_dock.hide()
  3107. else:
  3108. self.ui.shell_dock.show()
  3109. def on_edit_join(self, name=None):
  3110. """
  3111. Callback for Edit->Join. Joins the selected geometry objects into
  3112. a new one.
  3113. :return: None
  3114. """
  3115. self.report_usage("on_edit_join()")
  3116. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3117. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3118. tooldias = []
  3119. geo_type_list = set()
  3120. objs = self.collection.get_selected()
  3121. for obj in objs:
  3122. geo_type_list.add(obj.multigeo)
  3123. # if len(geo_type_list) == 1 means that all list elements are the same
  3124. if len(geo_type_list) != 1:
  3125. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  3126. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3127. "convert from one to another and retry joining \n"
  3128. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3129. "the result may not be what was expected. \n"
  3130. "Check the generated GCODE."))
  3131. return
  3132. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3133. if True in geo_type_list:
  3134. def initialize(obj, app):
  3135. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3136. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3137. for v in obj.tools.values():
  3138. v['data']['name'] = obj_name_multi
  3139. self.new_object("geometry", obj_name_multi, initialize)
  3140. else:
  3141. def initialize(obj, app):
  3142. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3143. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3144. for v in obj.tools.values():
  3145. v['data']['name'] = obj_name_single
  3146. self.new_object("geometry", obj_name_single, initialize)
  3147. self.should_we_save = True
  3148. def on_edit_join_exc(self):
  3149. """
  3150. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  3151. a new one.
  3152. :return: None
  3153. """
  3154. self.report_usage("on_edit_join_exc()")
  3155. objs = self.collection.get_selected()
  3156. for obj in objs:
  3157. if not isinstance(obj, FlatCAMExcellon):
  3158. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  3159. return
  3160. def initialize(obj, app):
  3161. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3162. self.new_object("excellon", 'Combo_Excellon', initialize)
  3163. self.should_we_save = True
  3164. def on_edit_join_grb(self):
  3165. """
  3166. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3167. a new one.
  3168. :return: None
  3169. """
  3170. self.report_usage("on_edit_join_grb()")
  3171. objs = self.collection.get_selected()
  3172. for obj in objs:
  3173. if not isinstance(obj, FlatCAMGerber):
  3174. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  3175. return
  3176. def initialize(obj, app):
  3177. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3178. self.new_object("gerber", 'Combo_Gerber', initialize)
  3179. self.should_we_save = True
  3180. def on_convert_singlegeo_to_multigeo(self):
  3181. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3182. obj = self.collection.get_active()
  3183. if obj is None:
  3184. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  3185. return
  3186. if not isinstance(obj, FlatCAMGeometry):
  3187. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  3188. return
  3189. obj.multigeo = True
  3190. for tooluid, dict_value in obj.tools.items():
  3191. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3192. if not isinstance(obj.solid_geometry, list):
  3193. obj.solid_geometry = [obj.solid_geometry]
  3194. obj.solid_geometry[:] = []
  3195. obj.plot()
  3196. self.should_we_save = True
  3197. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  3198. def on_convert_multigeo_to_singlegeo(self):
  3199. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3200. obj = self.collection.get_active()
  3201. if obj is None:
  3202. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  3203. return
  3204. if not isinstance(obj, FlatCAMGeometry):
  3205. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  3206. return
  3207. obj.multigeo = False
  3208. total_solid_geometry = []
  3209. for tooluid, dict_value in obj.tools.items():
  3210. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3211. # clear the original geometry
  3212. dict_value['solid_geometry'][:] = []
  3213. obj.solid_geometry = deepcopy(total_solid_geometry)
  3214. obj.plot()
  3215. self.should_we_save = True
  3216. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  3217. def on_options_dict_change(self, field):
  3218. self.options_write_form_field(field)
  3219. if field == "units":
  3220. self.set_screen_units(self.options['units'])
  3221. def on_defaults_dict_change(self, field):
  3222. self.defaults_write_form_field(field)
  3223. if field == "units":
  3224. self.set_screen_units(self.defaults['units'])
  3225. def set_screen_units(self, units):
  3226. self.ui.units_label.setText("[" + units.lower() + "]")
  3227. def on_toggle_units(self, no_pref=False):
  3228. """
  3229. Callback for the Units radio-button change in the Options tab.
  3230. Changes the application's default units or the current project's units.
  3231. If changing the project's units, the change propagates to all of
  3232. the objects in the project.
  3233. :return: None
  3234. """
  3235. self.report_usage("on_toggle_units")
  3236. if self.toggle_units_ignore:
  3237. return
  3238. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3239. # If option is the same, then ignore
  3240. if new_units == self.defaults["units"].upper():
  3241. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3242. return
  3243. # Options to scale
  3244. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3245. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  3246. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3247. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3248. "excellon_z_pdepth",
  3249. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3250. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3251. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3252. "geometry_feedrate_probe",
  3253. 'cncjob_tooldia',
  3254. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3255. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  3256. "tools_2sided_drilldia", "tools_film_boundary",
  3257. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3258. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3259. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3260. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3261. "tools_transform_offset_y",
  3262. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3263. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3264. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3265. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3266. 'global_gridx', 'global_gridy', 'global_snap_max']
  3267. def scale_options(sfactor):
  3268. for dim in dimensions:
  3269. if dim == 'excellon_toolchangexy':
  3270. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3271. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3272. coords_xy[0] *= sfactor
  3273. coords_xy[1] *= sfactor
  3274. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3275. elif dim == 'geometry_toolchangexy':
  3276. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3277. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3278. coords_xy[0] *= sfactor
  3279. coords_xy[1] *= sfactor
  3280. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3281. elif dim == 'geometry_cnctooldia':
  3282. tools_diameters = []
  3283. try:
  3284. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3285. tools_diameters = [eval(a) for a in tools_string if a != '']
  3286. except Exception as e:
  3287. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3288. self.options['geometry_cnctooldia'] = ''
  3289. for t in range(len(tools_diameters)):
  3290. tools_diameters[t] *= sfactor
  3291. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  3292. elif dim == 'tools_ncctools':
  3293. ncctools = []
  3294. try:
  3295. tools_string = self.defaults["tools_ncctools"].split(",")
  3296. ncctools = [eval(a) for a in tools_string if a != '']
  3297. except Exception as e:
  3298. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3299. self.options['tools_ncctools'] = ''
  3300. for t in range(len(ncctools)):
  3301. ncctools[t] *= sfactor
  3302. self.options['tools_ncctools'] += "%f," % ncctools[t]
  3303. elif dim == 'tools_solderpaste_tools':
  3304. sptools = []
  3305. try:
  3306. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3307. sptools = [eval(a) for a in tools_string if a != '']
  3308. except Exception as e:
  3309. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3310. self.options['tools_solderpaste_tools'] = ""
  3311. for t in range(len(sptools)):
  3312. sptools[t] *= sfactor
  3313. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  3314. elif dim == 'tools_solderpaste_xy_toolchange':
  3315. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3316. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3317. sp_coords[0] *= sfactor
  3318. sp_coords[1] *= sfactor
  3319. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3320. elif dim == 'global_gridx' or dim == 'global_gridy':
  3321. if new_units == 'IN':
  3322. val = 0.1
  3323. try:
  3324. val = float(self.defaults[dim]) * sfactor
  3325. except Exception as e:
  3326. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3327. self.options[dim] = float('%.6f' % val)
  3328. else:
  3329. val = 0.1
  3330. try:
  3331. val = float(self.defaults[dim]) * sfactor
  3332. except Exception as e:
  3333. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3334. self.options[dim] = float('%.4f' % val)
  3335. else:
  3336. val = 0.1
  3337. try:
  3338. val = float(self.options[dim]) * sfactor
  3339. except Exception as e:
  3340. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3341. self.options[dim] = val
  3342. def scale_defaults(sfactor):
  3343. for dim in dimensions:
  3344. if dim == 'excellon_toolchangexy':
  3345. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3346. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3347. coords_xy[0] *= sfactor
  3348. coords_xy[1] *= sfactor
  3349. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3350. elif dim == 'geometry_toolchangexy':
  3351. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3352. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3353. coords_xy[0] *= sfactor
  3354. coords_xy[1] *= sfactor
  3355. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3356. elif dim == 'geometry_cnctooldia':
  3357. tools_diameters = []
  3358. try:
  3359. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3360. tools_diameters = [eval(a) for a in tools_string if a != '']
  3361. except Exception as e:
  3362. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3363. self.defaults['geometry_cnctooldia'] = ''
  3364. for t in range(len(tools_diameters)):
  3365. tools_diameters[t] *= sfactor
  3366. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  3367. elif dim == 'tools_ncctools':
  3368. ncctools = []
  3369. try:
  3370. tools_string = self.defaults["tools_ncctools"].split(",")
  3371. ncctools = [eval(a) for a in tools_string if a != '']
  3372. except Exception as e:
  3373. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3374. self.defaults['tools_ncctools'] = ''
  3375. for t in range(len(ncctools)):
  3376. ncctools[t] *= sfactor
  3377. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  3378. elif dim == 'tools_solderpaste_tools':
  3379. sptools = []
  3380. try:
  3381. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3382. sptools = [eval(a) for a in tools_string if a != '']
  3383. except Exception as e:
  3384. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3385. self.defaults['tools_solderpaste_tools'] = ""
  3386. for t in range(len(sptools)):
  3387. sptools[t] *= sfactor
  3388. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  3389. elif dim == 'tools_solderpaste_xy_toolchange':
  3390. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3391. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3392. sp_coords[0] *= sfactor
  3393. sp_coords[1] *= sfactor
  3394. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  3395. elif dim == 'global_gridx' or dim == 'global_gridy':
  3396. if new_units == 'IN':
  3397. val = 0.1
  3398. try:
  3399. val = float(self.defaults[dim]) * sfactor
  3400. except Exception as e:
  3401. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3402. self.defaults[dim] = float('%.6f' % val)
  3403. else:
  3404. val = 0.1
  3405. try:
  3406. val = float(self.defaults[dim]) * sfactor
  3407. except Exception as e:
  3408. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3409. self.defaults[dim] = float('%.4f' % val)
  3410. else:
  3411. val = 0.1
  3412. try:
  3413. val = float(self.defaults[dim]) * sfactor
  3414. except Exception as e:
  3415. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3416. self.defaults[dim] = val
  3417. # The scaling factor depending on choice of units.
  3418. factor = 1/25.4
  3419. if new_units == 'MM':
  3420. factor = 25.4
  3421. # Changing project units. Warn user.
  3422. msgbox = QtWidgets.QMessageBox()
  3423. msgbox.setWindowTitle(_("Toggle Units"))
  3424. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3425. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3426. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  3427. "properties of all objects to be scaled accordingly.\nContinue?"))
  3428. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3429. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3430. msgbox.setDefaultButton(bt_ok)
  3431. msgbox.exec_()
  3432. response = msgbox.clickedButton()
  3433. if response == bt_ok:
  3434. if no_pref is False:
  3435. self.options_read_form()
  3436. scale_options(factor)
  3437. self.options_write_form()
  3438. self.defaults_read_form()
  3439. scale_defaults(factor)
  3440. self.defaults_write_form(fl_units=new_units)
  3441. # save the defaults to file, some may assume that the conversion is enough and it's not
  3442. self.on_save_button()
  3443. self.should_we_save = True
  3444. # change this only if the workspace is active
  3445. if self.defaults['global_workspace'] is True:
  3446. self.plotcanvas.draw_workspace()
  3447. # adjust the grid values on the main toolbar
  3448. dec = 6 if new_units == 'IN'else 4
  3449. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  3450. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  3451. if not self.ui.grid_gap_link_cb.isChecked():
  3452. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  3453. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  3454. for obj in self.collection.get_list():
  3455. obj.convert_units(new_units)
  3456. # make that the properties stored in the object are also updated
  3457. self.object_changed.emit(obj)
  3458. obj.build_ui()
  3459. current = self.collection.get_active()
  3460. if current is not None:
  3461. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3462. if not isinstance(current, FlatCAMGeometry):
  3463. current.to_form()
  3464. self.plot_all()
  3465. self.inform.emit(_("[success] Converted units to %s") % new_units)
  3466. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  3467. self.set_screen_units(new_units)
  3468. else:
  3469. # Undo toggling
  3470. self.toggle_units_ignore = True
  3471. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3472. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3473. else:
  3474. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3475. self.toggle_units_ignore = False
  3476. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  3477. self.options_read_form()
  3478. self.defaults_read_form()
  3479. def on_toggle_units_click(self):
  3480. try:
  3481. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3482. except (TypeError, AttributeError):
  3483. pass
  3484. if self.defaults["units"] == 'MM':
  3485. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3486. else:
  3487. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3488. self.on_toggle_units(no_pref=True)
  3489. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3490. lambda: self.on_toggle_units(no_pref=False))
  3491. def on_fullscreen(self):
  3492. self.report_usage("on_fullscreen()")
  3493. if self.toggle_fscreen is False:
  3494. if sys.platform == 'win32':
  3495. self.ui.showFullScreen()
  3496. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3497. tb.setVisible(False)
  3498. self.ui.splitter_left.setVisible(False)
  3499. self.toggle_fscreen = True
  3500. else:
  3501. if sys.platform == 'win32':
  3502. self.ui.showNormal()
  3503. self.restore_toolbar_view()
  3504. self.ui.splitter_left.setVisible(True)
  3505. self.toggle_fscreen = False
  3506. def on_toggle_plotarea(self):
  3507. self.report_usage("on_toggle_plotarea()")
  3508. try:
  3509. name = self.ui.plot_tab_area.widget(0).objectName()
  3510. except AttributeError:
  3511. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3512. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3513. self.ui.plot_tab_area.protectTab(0)
  3514. return
  3515. if name != 'plotarea':
  3516. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3517. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3518. self.ui.plot_tab_area.protectTab(0)
  3519. else:
  3520. self.ui.plot_tab_area.closeTab(0)
  3521. def on_toggle_notebook(self):
  3522. if self.ui.splitter.sizes()[0] == 0:
  3523. self.ui.splitter.setSizes([1, 1])
  3524. else:
  3525. self.ui.splitter.setSizes([0, 1])
  3526. def on_toggle_axis(self):
  3527. self.report_usage("on_toggle_axis()")
  3528. if self.toggle_axis is False:
  3529. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3530. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3531. self.plotcanvas.redraw()
  3532. self.toggle_axis = True
  3533. else:
  3534. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3535. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3536. self.plotcanvas.redraw()
  3537. self.toggle_axis = False
  3538. def on_toggle_grid(self):
  3539. self.report_usage("on_toggle_grid()")
  3540. self.ui.grid_snap_btn.trigger()
  3541. def on_options_combo_change(self, sel):
  3542. """
  3543. Called when the combo box to choose between application defaults and
  3544. project option changes value. The corresponding variables are
  3545. copied to the UI.
  3546. :param sel: The option index that was chosen.
  3547. :return: None
  3548. """
  3549. # combo_sel = self.ui.notebook.combo_options.get_active()
  3550. App.log.debug("Options --> %s" % sel)
  3551. # form = [self.defaults_form, self.options_form][sel]
  3552. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3553. if sel == 0:
  3554. self.gen_form = self.ui.general_defaults_form
  3555. self.ger_form = self.ui.gerber_defaults_form
  3556. self.exc_form = self.ui.excellon_defaults_form
  3557. self.geo_form = self.ui.geometry_defaults_form
  3558. self.cnc_form = self.ui.cncjob_defaults_form
  3559. self.tools_form = self.ui.tools_defaults_form
  3560. elif sel == 1:
  3561. self.gen_form = self.ui.general_options_form
  3562. self.ger_form = self.ui.gerber_options_form
  3563. self.exc_form = self.ui.excellon_options_form
  3564. self.geo_form = self.ui.geometry_options_form
  3565. self.cnc_form = self.ui.cncjob_options_form
  3566. self.tools_form = self.ui.tools_options_form
  3567. else:
  3568. return
  3569. try:
  3570. self.ui.general_scroll_area.takeWidget()
  3571. except:
  3572. self.log.debug("Nothing to remove")
  3573. self.ui.general_scroll_area.setWidget(self.gen_form)
  3574. self.gen_form.show()
  3575. try:
  3576. self.ui.gerber_scroll_area.takeWidget()
  3577. except:
  3578. self.log.debug("Nothing to remove")
  3579. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3580. self.ger_form.show()
  3581. try:
  3582. self.ui.excellon_scroll_area.takeWidget()
  3583. except:
  3584. self.log.debug("Nothing to remove")
  3585. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3586. self.exc_form.show()
  3587. try:
  3588. self.ui.geometry_scroll_area.takeWidget()
  3589. except:
  3590. self.log.debug("Nothing to remove")
  3591. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3592. self.geo_form.show()
  3593. try:
  3594. self.ui.cncjob_scroll_area.takeWidget()
  3595. except:
  3596. self.log.debug("Nothing to remove")
  3597. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3598. self.cnc_form.show()
  3599. try:
  3600. self.ui.tools_scroll_area.takeWidget()
  3601. except:
  3602. self.log.debug("Nothing to remove")
  3603. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3604. self.tools_form.show()
  3605. self.log.debug("Finished GUI form initialization.")
  3606. # self.options2form()
  3607. def on_excellon_defaults_button(self):
  3608. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3609. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3610. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3611. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3612. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3613. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3614. log.debug("Excellon app defaults loaded ...")
  3615. def on_excellon_options_button(self):
  3616. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3617. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3618. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3619. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3620. self.options_form_fields["excellon_zeros"].set_value('L')
  3621. self.options_form_fields["excellon_units"].set_value('INCH')
  3622. log.debug("Excellon options defaults loaded ...")
  3623. # Setting plot colors handlers
  3624. def on_pf_color_entry(self):
  3625. self.defaults['global_plot_fill'] = \
  3626. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3627. self.defaults['global_plot_fill'][7:9]
  3628. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3629. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3630. def on_pf_color_button(self):
  3631. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3632. c_dialog = QtWidgets.QColorDialog()
  3633. plot_fill_color = c_dialog.getColor(initial=current_color)
  3634. if plot_fill_color.isValid() is False:
  3635. return
  3636. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3637. "background-color:%s" % str(plot_fill_color.name()))
  3638. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3639. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3640. self.defaults['global_plot_fill'] = new_val
  3641. def on_pf_color_spinner(self):
  3642. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3643. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3644. self.defaults['global_plot_fill'] = \
  3645. self.defaults['global_plot_fill'][:7] + \
  3646. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3647. self.defaults['global_plot_line'] = \
  3648. self.defaults['global_plot_line'][:7] + \
  3649. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3650. def on_pf_color_slider(self):
  3651. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3652. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3653. def on_pl_color_entry(self):
  3654. self.defaults['global_plot_line'] = \
  3655. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3656. self.defaults['global_plot_line'][7:9]
  3657. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3658. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3659. def on_pl_color_button(self):
  3660. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3661. # print(current_color)
  3662. c_dialog = QtWidgets.QColorDialog()
  3663. plot_line_color = c_dialog.getColor(initial=current_color)
  3664. if plot_line_color.isValid() is False:
  3665. return
  3666. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3667. "background-color:%s" % str(plot_line_color.name()))
  3668. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3669. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3670. self.defaults['global_plot_line'] = new_val_line
  3671. # Setting selection colors (left - right) handlers
  3672. def on_sf_color_entry(self):
  3673. self.defaults['global_sel_fill'] = \
  3674. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3675. self.defaults['global_sel_fill'][7:9]
  3676. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3677. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3678. def on_sf_color_button(self):
  3679. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3680. c_dialog = QtWidgets.QColorDialog()
  3681. plot_fill_color = c_dialog.getColor(initial=current_color)
  3682. if plot_fill_color.isValid() is False:
  3683. return
  3684. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3685. "background-color:%s" % str(plot_fill_color.name()))
  3686. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3687. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3688. self.defaults['global_sel_fill'] = new_val
  3689. def on_sf_color_spinner(self):
  3690. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3691. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3692. self.defaults['global_sel_fill'] = \
  3693. self.defaults['global_sel_fill'][:7] + \
  3694. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3695. self.defaults['global_sel_line'] = \
  3696. self.defaults['global_sel_line'][:7] + \
  3697. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3698. def on_sf_color_slider(self):
  3699. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3700. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3701. def on_sl_color_entry(self):
  3702. self.defaults['global_sel_line'] = \
  3703. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3704. self.defaults['global_sel_line'][7:9]
  3705. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3706. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3707. def on_sl_color_button(self):
  3708. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3709. c_dialog = QtWidgets.QColorDialog()
  3710. plot_line_color = c_dialog.getColor(initial=current_color)
  3711. if plot_line_color.isValid() is False:
  3712. return
  3713. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3714. "background-color:%s" % str(plot_line_color.name()))
  3715. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3716. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3717. self.defaults['global_sel_line'] = new_val_line
  3718. # Setting selection colors (right - left) handlers
  3719. def on_alt_sf_color_entry(self):
  3720. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3721. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3722. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3723. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3724. def on_alt_sf_color_button(self):
  3725. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3726. c_dialog = QtWidgets.QColorDialog()
  3727. plot_fill_color = c_dialog.getColor(initial=current_color)
  3728. if plot_fill_color.isValid() is False:
  3729. return
  3730. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3731. "background-color:%s" % str(plot_fill_color.name()))
  3732. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3733. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3734. self.defaults['global_alt_sel_fill'] = new_val
  3735. def on_alt_sf_color_spinner(self):
  3736. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3737. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3738. self.defaults['global_alt_sel_fill'] = \
  3739. self.defaults['global_alt_sel_fill'][:7] + \
  3740. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3741. self.defaults['global_alt_sel_line'] = \
  3742. self.defaults['global_alt_sel_line'][:7] + \
  3743. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3744. def on_alt_sf_color_slider(self):
  3745. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3746. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3747. def on_alt_sl_color_entry(self):
  3748. self.defaults['global_alt_sel_line'] = \
  3749. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  3750. self.defaults['global_alt_sel_line'][7:9]
  3751. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3752. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3753. def on_alt_sl_color_button(self):
  3754. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3755. c_dialog = QtWidgets.QColorDialog()
  3756. plot_line_color = c_dialog.getColor(initial=current_color)
  3757. if plot_line_color.isValid() is False:
  3758. return
  3759. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3760. "background-color:%s" % str(plot_line_color.name()))
  3761. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3762. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3763. self.defaults['global_alt_sel_line'] = new_val_line
  3764. # Setting Editor colors
  3765. def on_draw_color_entry(self):
  3766. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3767. .draw_color_entry.get_value()
  3768. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3769. "background-color:%s" % str(self.defaults['global_draw_color']))
  3770. def on_draw_color_button(self):
  3771. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3772. c_dialog = QtWidgets.QColorDialog()
  3773. draw_color = c_dialog.getColor(initial=current_color)
  3774. if draw_color.isValid() is False:
  3775. return
  3776. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3777. "background-color:%s" % str(draw_color.name()))
  3778. new_val = str(draw_color.name())
  3779. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3780. self.defaults['global_draw_color'] = new_val
  3781. def on_sel_draw_color_entry(self):
  3782. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3783. .sel_draw_color_entry.get_value()
  3784. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3785. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3786. def on_sel_draw_color_button(self):
  3787. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3788. c_dialog = QtWidgets.QColorDialog()
  3789. sel_draw_color = c_dialog.getColor(initial=current_color)
  3790. if sel_draw_color.isValid() is False:
  3791. return
  3792. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3793. "background-color:%s" % str(sel_draw_color.name()))
  3794. new_val_sel = str(sel_draw_color.name())
  3795. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3796. self.defaults['global_sel_draw_color'] = new_val_sel
  3797. def on_proj_color_entry(self):
  3798. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  3799. .proj_color_entry.get_value()
  3800. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3801. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  3802. def on_proj_color_button(self):
  3803. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  3804. c_dialog = QtWidgets.QColorDialog()
  3805. proj_color = c_dialog.getColor(initial=current_color)
  3806. if proj_color.isValid() is False:
  3807. return
  3808. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3809. "background-color:%s" % str(proj_color.name()))
  3810. new_val_sel = str(proj_color.name())
  3811. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  3812. self.defaults['global_proj_item_color'] = new_val_sel
  3813. def on_proj_color_dis_entry(self):
  3814. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  3815. .proj_color_dis_entry.get_value()
  3816. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3817. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  3818. def on_proj_color_dis_button(self):
  3819. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  3820. c_dialog = QtWidgets.QColorDialog()
  3821. proj_color = c_dialog.getColor(initial=current_color)
  3822. if proj_color.isValid() is False:
  3823. return
  3824. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3825. "background-color:%s" % str(proj_color.name()))
  3826. new_val_sel = str(proj_color.name())
  3827. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  3828. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3829. def on_annotation_fontcolor_entry(self):
  3830. self.defaults['cncjob_annotation_fontcolor'] = \
  3831. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  3832. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  3833. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  3834. def on_annotation_fontcolor_button(self):
  3835. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  3836. c_dialog = QtWidgets.QColorDialog()
  3837. annotation_color = c_dialog.getColor(initial=current_color)
  3838. if annotation_color.isValid() is False:
  3839. return
  3840. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  3841. "background-color:%s" % str(annotation_color.name()))
  3842. new_val_sel = str(annotation_color.name())
  3843. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  3844. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3845. def on_notebook_tab_rmb_click(self, checked):
  3846. self.ui.notebook.set_detachable(val=checked)
  3847. self.defaults["global_tabs_detachable"] = checked
  3848. def on_plot_area_tab_rmb_click(self, checked):
  3849. self.ui.plot_tab_area.set_detachable(val=checked)
  3850. self.defaults["global_tabs_detachable"] = checked
  3851. def on_deselect_all(self):
  3852. self.collection.set_all_inactive()
  3853. self.delete_selection_shape()
  3854. def on_workspace_modified(self):
  3855. self.save_defaults(silent=True)
  3856. self.plotcanvas.draw_workspace()
  3857. def on_workspace(self):
  3858. self.report_usage("on_workspace()")
  3859. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3860. self.plotcanvas.restore_workspace()
  3861. else:
  3862. self.plotcanvas.delete_workspace()
  3863. self.save_defaults(silent=True)
  3864. def on_workspace_menu(self):
  3865. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3866. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3867. else:
  3868. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3869. self.on_workspace()
  3870. def on_layout(self, index=None, lay=None):
  3871. self.report_usage("on_layout()")
  3872. if lay:
  3873. current_layout = lay
  3874. else:
  3875. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3876. settings = QSettings("Open Source", "FlatCAM")
  3877. settings.setValue('layout', current_layout)
  3878. # This will write the setting to the platform specific storage.
  3879. del settings
  3880. # first remove the toolbars:
  3881. try:
  3882. self.ui.removeToolBar(self.ui.toolbarfile)
  3883. self.ui.removeToolBar(self.ui.toolbargeo)
  3884. self.ui.removeToolBar(self.ui.toolbarview)
  3885. self.ui.removeToolBar(self.ui.toolbarshell)
  3886. self.ui.removeToolBar(self.ui.toolbartools)
  3887. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3888. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3889. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3890. self.ui.removeToolBar(self.ui.snap_toolbar)
  3891. self.ui.removeToolBar(self.ui.toolbarshell)
  3892. except Exception as e:
  3893. pass
  3894. if current_layout == 'standard':
  3895. # ## TOOLBAR INSTALLATION # ##
  3896. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3897. self.ui.toolbarfile.setObjectName('File_TB')
  3898. self.ui.addToolBar(self.ui.toolbarfile)
  3899. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3900. self.ui.toolbargeo.setObjectName('Edit_TB')
  3901. self.ui.addToolBar(self.ui.toolbargeo)
  3902. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3903. self.ui.toolbarview.setObjectName('View_TB')
  3904. self.ui.addToolBar(self.ui.toolbarview)
  3905. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3906. self.ui.toolbarshell.setObjectName('Shell_TB')
  3907. self.ui.addToolBar(self.ui.toolbarshell)
  3908. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3909. self.ui.toolbartools.setObjectName('Tools_TB')
  3910. self.ui.addToolBar(self.ui.toolbartools)
  3911. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3912. self.ui.exc_edit_toolbar.setVisible(False)
  3913. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3914. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3915. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3916. self.ui.geo_edit_toolbar.setVisible(False)
  3917. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3918. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3919. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3920. self.ui.grb_edit_toolbar.setVisible(False)
  3921. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3922. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3923. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3924. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3925. # self.ui.snap_toolbar.setMaximumHeight(30)
  3926. self.ui.addToolBar(self.ui.snap_toolbar)
  3927. self.ui.corner_snap_btn.setVisible(False)
  3928. self.ui.snap_magnet.setVisible(False)
  3929. elif current_layout == 'compact':
  3930. # ## TOOLBAR INSTALLATION # ##
  3931. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3932. self.ui.toolbarfile.setObjectName('File_TB')
  3933. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3934. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3935. self.ui.toolbargeo.setObjectName('Edit_TB')
  3936. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3937. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3938. self.ui.toolbarview.setObjectName('View_TB')
  3939. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3940. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3941. self.ui.toolbarshell.setObjectName('Shell_TB')
  3942. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3943. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3944. self.ui.toolbartools.setObjectName('Tools_TB')
  3945. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3946. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3947. # self.ui.geo_edit_toolbar.setVisible(False)
  3948. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3949. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3950. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3951. # self.ui.grb_edit_toolbar.setVisible(False)
  3952. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3953. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  3954. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3955. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3956. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3957. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3958. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3959. self.ui.snap_toolbar.setMaximumHeight(30)
  3960. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3961. self.ui.corner_snap_btn.setVisible(True)
  3962. self.ui.snap_magnet.setVisible(True)
  3963. # add all the actions to the toolbars
  3964. self.ui.populate_toolbars()
  3965. # reconnect all the signals to the toolbar actions
  3966. self.connect_toolbar_signals()
  3967. self.ui.grid_snap_btn.setChecked(True)
  3968. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3969. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3970. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3971. self.ui.grid_gap_link_cb.setChecked(True)
  3972. def on_cnc_custom_parameters(self, signal_text):
  3973. if signal_text == 'Parameters':
  3974. return
  3975. else:
  3976. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3977. def on_save_button(self):
  3978. log.debug("App.on_save_button() --> Saving preferences to file.")
  3979. self.preferences_changed_flag = False
  3980. self.save_defaults(silent=False)
  3981. # load the defaults so they are updated into the app
  3982. self.load_defaults(filename='current_defaults')
  3983. # Re-fresh project options
  3984. self.on_options_app2project()
  3985. # save the notebook font size
  3986. settings = QSettings("Open Source", "FlatCAM")
  3987. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  3988. settings.setValue('notebook_font_size', fsize)
  3989. # save the axis font size
  3990. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  3991. settings.setValue('axis_font_size', g_fsize)
  3992. # This will write the setting to the platform specific storage.
  3993. del settings
  3994. def handlePrint(self):
  3995. self.report_usage("handlePrint()")
  3996. dialog = QtPrintSupport.QPrintDialog()
  3997. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3998. self.ui.code_editor.document().print_(dialog.printer())
  3999. def handlePreview(self):
  4000. self.report_usage("handlePreview()")
  4001. dialog = QtPrintSupport.QPrintPreviewDialog()
  4002. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4003. dialog.exec_()
  4004. def handleTextChanged(self):
  4005. # enable = not self.ui.code_editor.document().isEmpty()
  4006. # self.ui.buttonPrint.setEnabled(enable)
  4007. # self.ui.buttonPreview.setEnabled(enable)
  4008. pass
  4009. def handleOpen(self, filt=None):
  4010. self.report_usage("handleOpen()")
  4011. if filt:
  4012. _filter_ = filt
  4013. else:
  4014. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4015. "All Files (*.*)"
  4016. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4017. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4018. if path:
  4019. file = QtCore.QFile(path)
  4020. if file.open(QtCore.QIODevice.ReadOnly):
  4021. stream = QtCore.QTextStream(file)
  4022. self.gcode_edited = stream.readAll()
  4023. self.ui.code_editor.setPlainText(self.gcode_edited)
  4024. file.close()
  4025. def handleSaveGCode(self, name=None, filt=None):
  4026. self.report_usage("handleSaveGCode()")
  4027. if filt:
  4028. _filter_ = filt
  4029. else:
  4030. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4031. "All Files (*.*)"
  4032. if name:
  4033. obj_name = name
  4034. else:
  4035. try:
  4036. obj_name = self.collection.get_active().options['name']
  4037. except AttributeError:
  4038. obj_name = 'file'
  4039. if filt is None:
  4040. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4041. try:
  4042. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4043. caption=_("Export G-Code ..."),
  4044. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4045. filter=_filter_
  4046. )[0])
  4047. except TypeError:
  4048. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4049. if filename == "":
  4050. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  4051. return
  4052. else:
  4053. try:
  4054. my_gcode = self.ui.code_editor.toPlainText()
  4055. with open(filename, 'w') as f:
  4056. for line in my_gcode:
  4057. f.write(line)
  4058. except FileNotFoundError:
  4059. self.inform.emit(_("[WARNING] No such file or directory"))
  4060. return
  4061. except PermissionError:
  4062. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  4063. "Most likely another app is holding the file open and not accessible."))
  4064. return
  4065. # Just for adding it to the recent files list.
  4066. if self.defaults["global_open_style"] is False:
  4067. self.file_opened.emit("cncjob", filename)
  4068. self.file_saved.emit("cncjob", filename)
  4069. self.inform.emit(_("Saved to: %s") % filename)
  4070. def handleFindGCode(self):
  4071. self.report_usage("handleFindGCode()")
  4072. flags = QtGui.QTextDocument.FindCaseSensitively
  4073. text_to_be_found = self.ui.entryFind.get_value()
  4074. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4075. if r is False:
  4076. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4077. def handleReplaceGCode(self):
  4078. self.report_usage("handleReplaceGCode()")
  4079. old = self.ui.entryFind.get_value()
  4080. new = self.ui.entryReplace.get_value()
  4081. if self.ui.sel_all_cb.isChecked():
  4082. while True:
  4083. cursor = self.ui.code_editor.textCursor()
  4084. cursor.beginEditBlock()
  4085. flags = QtGui.QTextDocument.FindCaseSensitively
  4086. # self.ui.editor is the QPlainTextEdit
  4087. r = self.ui.code_editor.find(str(old), flags)
  4088. if r:
  4089. qc = self.ui.code_editor.textCursor()
  4090. if qc.hasSelection():
  4091. qc.insertText(new)
  4092. else:
  4093. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4094. break
  4095. # Mark end of undo block
  4096. cursor.endEditBlock()
  4097. else:
  4098. cursor = self.ui.code_editor.textCursor()
  4099. cursor.beginEditBlock()
  4100. qc = self.ui.code_editor.textCursor()
  4101. if qc.hasSelection():
  4102. qc.insertText(new)
  4103. # Mark end of undo block
  4104. cursor.endEditBlock()
  4105. def on_tool_add_keypress(self):
  4106. # ## Current application units in Upper Case
  4107. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4108. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4109. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4110. if notebook_widget_name == 'selected_tab':
  4111. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4112. # Tool add works for Geometry only if Advanced is True in Preferences
  4113. if self.defaults["global_app_level"] == 'a':
  4114. tool_add_popup = FCInputDialog(title="New Tool ...",
  4115. text='Enter a Tool Diameter:',
  4116. min=0.0000, max=99.9999, decimals=4)
  4117. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4118. val, ok = tool_add_popup.get_value()
  4119. if ok:
  4120. if float(val) == 0:
  4121. self.inform.emit(
  4122. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4123. return
  4124. self.collection.get_active().on_tool_add(dia=float(val))
  4125. else:
  4126. self.inform.emit(
  4127. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4128. else:
  4129. msgbox = QtWidgets.QMessageBox()
  4130. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4131. "Go to Preferences -> General - Show Advanced Options."))
  4132. msgbox.setWindowTitle("Tool adding ...")
  4133. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  4134. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4135. msgbox.setDefaultButton(bt_ok)
  4136. msgbox.exec_()
  4137. # work only if the notebook tab on focus is the Tools_Tab
  4138. if notebook_widget_name == 'tool_tab':
  4139. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4140. tool_add_popup = FCInputDialog(title="New Tool ...",
  4141. text='Enter a Tool Diameter:',
  4142. min=0.0000, max=99.9999, decimals=4)
  4143. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  4144. val, ok = tool_add_popup.get_value()
  4145. # and only if the tool is NCC Tool
  4146. if tool_widget == self.ncclear_tool.toolName:
  4147. if ok:
  4148. if float(val) == 0:
  4149. self.inform.emit(
  4150. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4151. return
  4152. self.ncclear_tool.on_tool_add(dia=float(val))
  4153. else:
  4154. self.inform.emit(
  4155. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4156. # and only if the tool is Paint Area Tool
  4157. elif tool_widget == self.paint_tool.toolName:
  4158. if ok:
  4159. if float(val) == 0:
  4160. self.inform.emit(
  4161. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4162. return
  4163. self.paint_tool.on_tool_add(dia=float(val))
  4164. else:
  4165. self.inform.emit(
  4166. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4167. # and only if the tool is Solder Paste Dispensing Tool
  4168. elif tool_widget == self.paste_tool.toolName:
  4169. if ok:
  4170. if float(val) == 0:
  4171. self.inform.emit(
  4172. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  4173. return
  4174. self.paste_tool.on_tool_add(dia=float(val))
  4175. else:
  4176. self.inform.emit(
  4177. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  4178. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4179. # See description bellow.
  4180. def on_delete_keypress(self):
  4181. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4182. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4183. if notebook_widget_name == 'selected_tab':
  4184. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  4185. self.collection.get_active().on_tool_delete()
  4186. # work only if the notebook tab on focus is the Tools_Tab
  4187. elif notebook_widget_name == 'tool_tab':
  4188. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4189. # and only if the tool is NCC Tool
  4190. if tool_widget == self.ncclear_tool.toolName:
  4191. self.ncclear_tool.on_tool_delete()
  4192. # and only if the tool is Paint Tool
  4193. elif tool_widget == self.paint_tool.toolName:
  4194. self.paint_tool.on_tool_delete()
  4195. # and only if the tool is Solder Paste Dispensing Tool
  4196. elif tool_widget == self.paste_tool.toolName:
  4197. self.paste_tool.on_tool_delete()
  4198. else:
  4199. self.on_delete()
  4200. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4201. # some screens you have to be careful where you hover with your mouse.
  4202. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4203. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4204. # Complicated, I know :)
  4205. def on_delete(self):
  4206. """
  4207. Delete the currently selected FlatCAMObjs.
  4208. :return: None
  4209. """
  4210. self.report_usage("on_delete()")
  4211. response = None
  4212. bt_ok = None
  4213. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4214. # a geometry object before we update it.
  4215. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4216. and self.grb_editor.editor_active is False:
  4217. if self.defaults["global_delete_confirmation"] is True:
  4218. msgbox = QtWidgets.QMessageBox()
  4219. msgbox.setWindowTitle(_("Delete objects"))
  4220. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  4221. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4222. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4223. "the selected objects?"))
  4224. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4225. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4226. msgbox.setDefaultButton(bt_ok)
  4227. msgbox.exec_()
  4228. response = msgbox.clickedButton()
  4229. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  4230. if self.collection.get_active():
  4231. self.log.debug("App.on_delete()")
  4232. while self.collection.get_active():
  4233. obj_active = self.collection.get_active()
  4234. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  4235. if isinstance(obj_active, FlatCAMGerber):
  4236. for el in obj_active.mark_shapes:
  4237. obj_active.mark_shapes[el].clear(update=True)
  4238. obj_active.mark_shapes[el].enabled = False
  4239. obj_active.mark_shapes[el] = None
  4240. elif isinstance(obj_active, FlatCAMCNCjob):
  4241. try:
  4242. obj_active.annotation.clear(update=True)
  4243. obj_active.annotation.enabled = False
  4244. except AttributeError:
  4245. pass
  4246. self.delete_first_selected()
  4247. self.inform.emit(_("Object(s) deleted ..."))
  4248. # make sure that the selection shape is deleted, too
  4249. self.delete_selection_shape()
  4250. else:
  4251. self.inform.emit(_("Failed. No object(s) selected..."))
  4252. else:
  4253. self.inform.emit(_("Save the work in Editor and try again ..."))
  4254. def delete_first_selected(self):
  4255. # Keep this for later
  4256. try:
  4257. sel_obj = self.collection.get_active()
  4258. name = sel_obj.options["name"]
  4259. except AttributeError:
  4260. self.log.debug("Nothing selected for deletion")
  4261. return
  4262. # Remove from dictionary
  4263. self.collection.delete_active()
  4264. # Clear form
  4265. self.setup_component_editor()
  4266. self.inform.emit("Object deleted: %s" % name)
  4267. def on_set_origin(self):
  4268. """
  4269. Set the origin to the left mouse click position
  4270. :return: None
  4271. """
  4272. # display the message for the user
  4273. # and ask him to click on the desired position
  4274. self.report_usage("on_set_origin()")
  4275. self.inform.emit(_('Click to set the origin ...'))
  4276. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  4277. def on_jump_to(self, custom_location=None, fit_center=True):
  4278. """
  4279. Jump to a location by setting the mouse cursor location
  4280. :return:
  4281. """
  4282. self.report_usage("on_jump_to()")
  4283. if not custom_location:
  4284. dia_box = Dialog_box(title=_("Jump to ..."),
  4285. label=_("Enter the coordinates in format X,Y:"),
  4286. icon=QtGui.QIcon('share/jump_to16.png'))
  4287. if dia_box.ok is True:
  4288. try:
  4289. location = eval(dia_box.location)
  4290. if not isinstance(location, tuple):
  4291. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4292. return
  4293. except:
  4294. return
  4295. else:
  4296. return
  4297. else:
  4298. location = custom_location
  4299. if fit_center:
  4300. self.plotcanvas.fit_center(loc=location)
  4301. cursor = QtGui.QCursor()
  4302. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4303. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  4304. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  4305. self.inform.emit(_("[success] Done."))
  4306. def on_copy_object(self):
  4307. self.report_usage("on_copy_object()")
  4308. def initialize(obj_init, app):
  4309. obj_init.solid_geometry = obj.solid_geometry
  4310. try:
  4311. obj_init.follow_geometry = obj.follow_geometry
  4312. except AttributeError:
  4313. pass
  4314. try:
  4315. obj_init.apertures = obj.apertures
  4316. except AttributeError:
  4317. pass
  4318. try:
  4319. if obj.tools:
  4320. obj_init.tools = obj.tools
  4321. except Exception as e:
  4322. log.debug("App.on_copy_object() --> %s" % str(e))
  4323. def initialize_excellon(obj_init, app):
  4324. obj_init.tools = obj.tools
  4325. # drills are offset, so they need to be deep copied
  4326. obj_init.drills = deepcopy(obj.drills)
  4327. # slots are offset, so they need to be deep copied
  4328. obj_init.slots = deepcopy(obj.slots)
  4329. obj_init.create_geometry()
  4330. for obj in self.collection.get_selected():
  4331. obj_name = obj.options["name"]
  4332. try:
  4333. if isinstance(obj, FlatCAMExcellon):
  4334. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4335. elif isinstance(obj, FlatCAMGerber):
  4336. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4337. elif isinstance(obj, FlatCAMGeometry):
  4338. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4339. except Exception as e:
  4340. return "Operation failed: %s" % str(e)
  4341. def on_copy_object2(self, custom_name):
  4342. def initialize_geometry(obj_init, app):
  4343. obj_init.solid_geometry = obj.solid_geometry
  4344. try:
  4345. obj_init.follow_geometry = obj.follow_geometry
  4346. except AttributeError:
  4347. pass
  4348. try:
  4349. obj_init.apertures = obj.apertures
  4350. except AttributeError:
  4351. pass
  4352. try:
  4353. if obj.tools:
  4354. obj_init.tools = obj.tools
  4355. except Exception as e:
  4356. log.debug("on_copy_object2() --> %s" % str(e))
  4357. def initialize_gerber(obj_init, app):
  4358. obj_init.solid_geometry = obj.solid_geometry
  4359. obj_init.apertures = deepcopy(obj.apertures)
  4360. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4361. def initialize_excellon(obj_init, app):
  4362. obj_init.tools = obj.tools
  4363. # drills are offset, so they need to be deep copied
  4364. obj_init.drills = deepcopy(obj.drills)
  4365. # slots are offset, so they need to be deep copied
  4366. obj_init.slots = deepcopy(obj.slots)
  4367. obj_init.create_geometry()
  4368. for obj in self.collection.get_selected():
  4369. obj_name = obj.options["name"]
  4370. try:
  4371. if isinstance(obj, FlatCAMExcellon):
  4372. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4373. elif isinstance(obj, FlatCAMGerber):
  4374. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4375. elif isinstance(obj, FlatCAMGeometry):
  4376. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4377. except Exception as e:
  4378. return "Operation failed: %s" % str(e)
  4379. def on_rename_object(self, text):
  4380. self.report_usage("on_rename_object()")
  4381. named_obj = self.collection.get_active()
  4382. for obj in named_obj:
  4383. if obj is list:
  4384. self.on_rename_object(text)
  4385. else:
  4386. try:
  4387. obj.options['name'] = text
  4388. except Exception as e:
  4389. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4390. def convert_any2geo(self):
  4391. self.report_usage("convert_any2geo()")
  4392. def initialize(obj_init, app):
  4393. obj_init.solid_geometry = obj.solid_geometry
  4394. try:
  4395. obj_init.follow_geometry = obj.follow_geometry
  4396. except AttributeError:
  4397. pass
  4398. try:
  4399. obj_init.apertures = obj.apertures
  4400. except AttributeError:
  4401. pass
  4402. try:
  4403. if obj.tools:
  4404. obj_init.tools = obj.tools
  4405. except AttributeError:
  4406. pass
  4407. def initialize_excellon(obj_init, app):
  4408. # objs = self.collection.get_selected()
  4409. # FlatCAMGeometry.merge(objs, obj)
  4410. solid_geo = []
  4411. for tool in obj.tools:
  4412. for geo in obj.tools[tool]['solid_geometry']:
  4413. solid_geo.append(geo)
  4414. obj_init.solid_geometry = deepcopy(solid_geo)
  4415. if not self.collection.get_selected():
  4416. log.warning("App.convert_any2geo --> No object selected")
  4417. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4418. return
  4419. for obj in self.collection.get_selected():
  4420. obj_name = obj.options["name"]
  4421. try:
  4422. if isinstance(obj, FlatCAMExcellon):
  4423. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4424. else:
  4425. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4426. except Exception as e:
  4427. return "Operation failed: %s" % str(e)
  4428. def convert_any2gerber(self):
  4429. self.report_usage("convert_any2gerber()")
  4430. def initialize_geometry(obj_init, app):
  4431. apertures = {}
  4432. apid = 0
  4433. apertures[str(apid)] = {}
  4434. apertures[str(apid)]['geometry'] = []
  4435. for obj_orig in obj.solid_geometry:
  4436. new_elem = dict()
  4437. new_elem['solid'] = obj_orig
  4438. new_elem['follow'] = obj_orig.exterior
  4439. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4440. apertures[str(apid)]['size'] = 0.0
  4441. apertures[str(apid)]['type'] = 'C'
  4442. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4443. obj_init.apertures = deepcopy(apertures)
  4444. def initialize_excellon(obj_init, app):
  4445. apertures = {}
  4446. apid = 10
  4447. for tool in obj.tools:
  4448. apertures[str(apid)] = {}
  4449. apertures[str(apid)]['geometry'] = []
  4450. for geo in obj.tools[tool]['solid_geometry']:
  4451. new_el = dict()
  4452. new_el['solid'] = geo
  4453. new_el['follow'] = geo.exterior
  4454. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4455. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4456. apertures[str(apid)]['type'] = 'C'
  4457. apid += 1
  4458. # create solid_geometry
  4459. solid_geometry = []
  4460. for apid in apertures:
  4461. for geo_el in apertures[apid]['geometry']:
  4462. solid_geometry.append(geo_el['solid'])
  4463. solid_geometry = MultiPolygon(solid_geometry)
  4464. solid_geometry = solid_geometry.buffer(0.0000001)
  4465. obj_init.solid_geometry = deepcopy(solid_geometry)
  4466. obj_init.apertures = deepcopy(apertures)
  4467. # clear the working objects (perhaps not necessary due of Python GC)
  4468. apertures.clear()
  4469. if not self.collection.get_selected():
  4470. log.warning("App.convert_any2gerber --> No object selected")
  4471. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4472. return
  4473. for obj in self.collection.get_selected():
  4474. obj_name = obj.options["name"]
  4475. try:
  4476. if isinstance(obj, FlatCAMExcellon):
  4477. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4478. elif isinstance(obj, FlatCAMGeometry):
  4479. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4480. else:
  4481. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4482. except Exception as e:
  4483. return "Operation failed: %s" % str(e)
  4484. def on_set_zero_click(self, event):
  4485. # this function will be available only for mouse left click
  4486. pos = []
  4487. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4488. if event.button == 1:
  4489. if self.grid_status() == True:
  4490. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4491. else:
  4492. pos = pos_canvas
  4493. x = 0 - pos[0]
  4494. y = 0 - pos[1]
  4495. for obj in self.collection.get_list():
  4496. obj.offset((x, y))
  4497. self.object_changed.emit(obj)
  4498. obj.plot()
  4499. # Update the object bounding box options
  4500. a, b, c, d = obj.bounds()
  4501. obj.options['xmin'] = a
  4502. obj.options['ymin'] = b
  4503. obj.options['xmax'] = c
  4504. obj.options['ymax'] = d
  4505. # self.plot_all(zoom=False)
  4506. self.inform.emit(_('[success] Origin set ...'))
  4507. self.plotcanvas.fit_view()
  4508. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4509. self.should_we_save = True
  4510. def on_selectall(self):
  4511. self.report_usage("on_selectall()")
  4512. # delete the possible selection box around a possible selected object
  4513. self.delete_selection_shape()
  4514. for name in self.collection.get_names():
  4515. self.collection.set_active(name)
  4516. curr_sel_obj = self.collection.get_by_name(name)
  4517. # create the selection box around the selected object
  4518. if self.defaults['global_selection_shape'] is True:
  4519. self.draw_selection_shape(curr_sel_obj)
  4520. def on_preferences(self):
  4521. # add the tab if it was closed
  4522. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4523. # delete the absolute and relative position and messages in the infobar
  4524. self.ui.position_label.setText("")
  4525. self.ui.rel_position_label.setText("")
  4526. # Switch plot_area to preferences page
  4527. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4528. self.ui.show()
  4529. # this disconnect() is done so the slot will be connected only once
  4530. try:
  4531. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  4532. except (TypeError, AttributeError):
  4533. pass
  4534. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  4535. # detect changes in the preferences
  4536. for idx in range(self.ui.pref_tab_area.count()):
  4537. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4538. try:
  4539. try:
  4540. tb.textEdited.disconnect(self.on_preferences_edited)
  4541. except (TypeError, AttributeError):
  4542. pass
  4543. tb.textEdited.connect(self.on_preferences_edited)
  4544. except AttributeError:
  4545. pass
  4546. try:
  4547. try:
  4548. tb.modificationChanged.disconnect(self.on_preferences_edited)
  4549. except (TypeError, AttributeError):
  4550. pass
  4551. tb.modificationChanged.connect(self.on_preferences_edited)
  4552. except AttributeError:
  4553. pass
  4554. try:
  4555. try:
  4556. tb.toggled.disconnect(self.on_preferences_edited)
  4557. except (TypeError, AttributeError):
  4558. pass
  4559. tb.toggled.connect(self.on_preferences_edited)
  4560. except AttributeError:
  4561. pass
  4562. try:
  4563. try:
  4564. tb.valueChanged.disconnect(self.on_preferences_edited)
  4565. except (TypeError, AttributeError):
  4566. pass
  4567. tb.valueChanged.connect(self.on_preferences_edited)
  4568. except AttributeError:
  4569. pass
  4570. try:
  4571. try:
  4572. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  4573. except (TypeError, AttributeError):
  4574. pass
  4575. tb.currentIndexChanged.connect(self.on_preferences_edited)
  4576. except AttributeError:
  4577. pass
  4578. def on_preferences_edited(self):
  4579. self.inform.emit(_("[WARNING_NOTCL] Preferences edited but not saved."))
  4580. self.preferences_changed_flag = True
  4581. def on_preferences_closed(self):
  4582. # disconnect
  4583. for idx in range(self.ui.pref_tab_area.count()):
  4584. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4585. try:
  4586. tb.textEdited.disconnect(self.on_preferences_edited)
  4587. except (TypeError, AttributeError):
  4588. pass
  4589. try:
  4590. tb.modificationChanged.disconnect(self.on_preferences_edited)
  4591. except (TypeError, AttributeError):
  4592. pass
  4593. try:
  4594. tb.toggled.disconnect(self.on_preferences_edited)
  4595. except (TypeError, AttributeError):
  4596. pass
  4597. try:
  4598. tb.valueChanged.disconnect(self.on_preferences_edited)
  4599. except (TypeError, AttributeError):
  4600. pass
  4601. try:
  4602. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  4603. except (TypeError, AttributeError):
  4604. pass
  4605. if self.preferences_changed_flag is True:
  4606. msgbox = QtWidgets.QMessageBox()
  4607. msgbox.setText(_("One or more values are changed.\n"
  4608. "Do you want to save the Preferences?"))
  4609. msgbox.setWindowTitle(_("Save Preferences"))
  4610. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4611. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4612. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4613. msgbox.setDefaultButton(bt_yes)
  4614. msgbox.exec_()
  4615. response = msgbox.clickedButton()
  4616. if response == bt_yes:
  4617. self.on_save_button()
  4618. self.inform.emit(_("[success] Preferences saved."))
  4619. else:
  4620. self.preferences_changed_flag = False
  4621. return
  4622. def on_flipy(self):
  4623. self.report_usage("on_flipy()")
  4624. obj_list = self.collection.get_selected()
  4625. xminlist = []
  4626. yminlist = []
  4627. xmaxlist = []
  4628. ymaxlist = []
  4629. if not obj_list:
  4630. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  4631. else:
  4632. try:
  4633. # first get a bounding box to fit all
  4634. for obj in obj_list:
  4635. xmin, ymin, xmax, ymax = obj.bounds()
  4636. xminlist.append(xmin)
  4637. yminlist.append(ymin)
  4638. xmaxlist.append(xmax)
  4639. ymaxlist.append(ymax)
  4640. # get the minimum x,y and maximum x,y for all objects selected
  4641. xminimal = min(xminlist)
  4642. yminimal = min(yminlist)
  4643. xmaximal = max(xmaxlist)
  4644. ymaximal = max(ymaxlist)
  4645. px = 0.5 * (xminimal + xmaximal)
  4646. py = 0.5 * (yminimal + ymaximal)
  4647. # execute mirroring
  4648. for obj in obj_list:
  4649. obj.mirror('X', [px, py])
  4650. obj.plot()
  4651. self.object_changed.emit(obj)
  4652. self.inform.emit(_("[success] Flip on Y axis done."))
  4653. except Exception as e:
  4654. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4655. return
  4656. def on_flipx(self):
  4657. self.report_usage("on_flipx()")
  4658. obj_list = self.collection.get_selected()
  4659. xminlist = []
  4660. yminlist = []
  4661. xmaxlist = []
  4662. ymaxlist = []
  4663. if not obj_list:
  4664. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  4665. else:
  4666. try:
  4667. # first get a bounding box to fit all
  4668. for obj in obj_list:
  4669. xmin, ymin, xmax, ymax = obj.bounds()
  4670. xminlist.append(xmin)
  4671. yminlist.append(ymin)
  4672. xmaxlist.append(xmax)
  4673. ymaxlist.append(ymax)
  4674. # get the minimum x,y and maximum x,y for all objects selected
  4675. xminimal = min(xminlist)
  4676. yminimal = min(yminlist)
  4677. xmaximal = max(xmaxlist)
  4678. ymaximal = max(ymaxlist)
  4679. px = 0.5 * (xminimal + xmaximal)
  4680. py = 0.5 * (yminimal + ymaximal)
  4681. # execute mirroring
  4682. for obj in obj_list:
  4683. obj.mirror('Y', [px, py])
  4684. obj.plot()
  4685. self.object_changed.emit(obj)
  4686. self.inform.emit(_("[success] Flip on X axis done."))
  4687. except Exception as e:
  4688. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4689. return
  4690. def on_rotate(self, silent=False, preset=None):
  4691. self.report_usage("on_rotate()")
  4692. obj_list = self.collection.get_selected()
  4693. xminlist = []
  4694. yminlist = []
  4695. xmaxlist = []
  4696. ymaxlist = []
  4697. if not obj_list:
  4698. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  4699. else:
  4700. if silent is False:
  4701. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4702. min=-360, max=360, decimals=4,
  4703. init_val=float(self.defaults['tools_transform_rotate']))
  4704. num, ok = rotatebox.get_value()
  4705. else:
  4706. num = preset
  4707. ok = True
  4708. if ok:
  4709. try:
  4710. # first get a bounding box to fit all
  4711. for obj in obj_list:
  4712. xmin, ymin, xmax, ymax = obj.bounds()
  4713. xminlist.append(xmin)
  4714. yminlist.append(ymin)
  4715. xmaxlist.append(xmax)
  4716. ymaxlist.append(ymax)
  4717. # get the minimum x,y and maximum x,y for all objects selected
  4718. xminimal = min(xminlist)
  4719. yminimal = min(yminlist)
  4720. xmaximal = max(xmaxlist)
  4721. ymaximal = max(ymaxlist)
  4722. px = 0.5 * (xminimal + xmaximal)
  4723. py = 0.5 * (yminimal + ymaximal)
  4724. for sel_obj in obj_list:
  4725. sel_obj.rotate(-float(num), point=(px, py))
  4726. sel_obj.plot()
  4727. self.object_changed.emit(sel_obj)
  4728. self.inform.emit(_("[success] Rotation done."))
  4729. except Exception as e:
  4730. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  4731. return
  4732. def on_skewx(self):
  4733. self.report_usage("on_skewx()")
  4734. obj_list = self.collection.get_selected()
  4735. xminlist = []
  4736. yminlist = []
  4737. if not obj_list:
  4738. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  4739. else:
  4740. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4741. min=-360, max=360, decimals=4,
  4742. init_val=float(self.defaults['tools_transform_skew_x']))
  4743. num, ok = skewxbox.get_value()
  4744. if ok:
  4745. # first get a bounding box to fit all
  4746. for obj in obj_list:
  4747. xmin, ymin, xmax, ymax = obj.bounds()
  4748. xminlist.append(xmin)
  4749. yminlist.append(ymin)
  4750. # get the minimum x,y and maximum x,y for all objects selected
  4751. xminimal = min(xminlist)
  4752. yminimal = min(yminlist)
  4753. for obj in obj_list:
  4754. obj.skew(num, 0, point=(xminimal, yminimal))
  4755. obj.plot()
  4756. self.object_changed.emit(obj)
  4757. self.inform.emit(_("[success] Skew on X axis done."))
  4758. def on_skewy(self):
  4759. self.report_usage("on_skewy()")
  4760. obj_list = self.collection.get_selected()
  4761. xminlist = []
  4762. yminlist = []
  4763. if not obj_list:
  4764. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  4765. else:
  4766. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4767. min=-360, max=360, decimals=4,
  4768. init_val=float(self.defaults['tools_transform_skew_y']))
  4769. num, ok = skewybox.get_value()
  4770. if ok:
  4771. # first get a bounding box to fit all
  4772. for obj in obj_list:
  4773. xmin, ymin, xmax, ymax = obj.bounds()
  4774. xminlist.append(xmin)
  4775. yminlist.append(ymin)
  4776. # get the minimum x,y and maximum x,y for all objects selected
  4777. xminimal = min(xminlist)
  4778. yminimal = min(yminlist)
  4779. for obj in obj_list:
  4780. obj.skew(0, num, point=(xminimal, yminimal))
  4781. obj.plot()
  4782. self.object_changed.emit(obj)
  4783. self.inform.emit(_("[success] Skew on Y axis done."))
  4784. def on_plots_updated(self):
  4785. """
  4786. Callback used to report when the plots have changed.
  4787. Adjust axes and zooms to fit.
  4788. :return: None
  4789. """
  4790. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  4791. self.on_zoom_fit(None)
  4792. self.collection.update_view()
  4793. # self.inform.emit(_("Plots updated ..."))
  4794. # TODO: Rework toolbar 'clear', 'replot' functions
  4795. def on_toolbar_replot(self):
  4796. """
  4797. Callback for toolbar button. Re-plots all objects.
  4798. :return: None
  4799. """
  4800. self.report_usage("on_toolbar_replot")
  4801. self.log.debug("on_toolbar_replot()")
  4802. try:
  4803. self.collection.get_active().read_form()
  4804. except AttributeError:
  4805. self.log.debug("on_toolbar_replot(): AttributeError")
  4806. pass
  4807. self.plot_all()
  4808. def on_row_activated(self, index):
  4809. if index.isValid():
  4810. if index.internalPointer().parent_item != self.collection.root_item:
  4811. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4812. self.collection.on_item_activated(index)
  4813. def grid_status(self):
  4814. if self.ui.grid_snap_btn.isChecked():
  4815. return True
  4816. else:
  4817. return False
  4818. def populate_cmenu_grids(self):
  4819. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4820. self.ui.cmenu_gridmenu.clear()
  4821. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4822. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  4823. grid_toggle.setCheckable(True)
  4824. if self.grid_status() == True:
  4825. grid_toggle.setChecked(True)
  4826. else:
  4827. grid_toggle.setChecked(False)
  4828. self.ui.cmenu_gridmenu.addSeparator()
  4829. for grid in sorted_list:
  4830. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4831. action.triggered.connect(self.set_grid)
  4832. self.ui.cmenu_gridmenu.addSeparator()
  4833. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  4834. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  4835. grid_add.triggered.connect(self.on_grid_add)
  4836. grid_delete.triggered.connect(self.on_grid_delete)
  4837. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4838. def set_grid(self):
  4839. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4840. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4841. def on_grid_add(self):
  4842. # ## Current application units in lower Case
  4843. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4844. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4845. text=_('Enter a Grid Value:'),
  4846. min=0.0000, max=99.9999, decimals=4)
  4847. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4848. val, ok = grid_add_popup.get_value()
  4849. if ok:
  4850. if float(val) == 0:
  4851. self.inform.emit(
  4852. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4853. return
  4854. else:
  4855. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4856. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4857. self.inform.emit(
  4858. _("[success] New Grid added ..."))
  4859. else:
  4860. self.inform.emit(
  4861. _("[WARNING_NOTCL] Grid already exists ..."))
  4862. else:
  4863. self.inform.emit(
  4864. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4865. def on_grid_delete(self):
  4866. # ## Current application units in lower Case
  4867. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4868. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4869. text='Enter a Grid Value:',
  4870. min=0.0000, max=99.9999, decimals=4)
  4871. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4872. val, ok = grid_del_popup.get_value()
  4873. if ok:
  4874. if float(val) == 0:
  4875. self.inform.emit(
  4876. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4877. return
  4878. else:
  4879. try:
  4880. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4881. except ValueError:
  4882. self.inform.emit(
  4883. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4884. return
  4885. self.inform.emit(
  4886. _("[success] Grid Value deleted ..."))
  4887. else:
  4888. self.inform.emit(
  4889. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4890. def on_shortcut_list(self):
  4891. self.report_usage("on_shortcut_list()")
  4892. # add the tab if it was closed
  4893. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4894. # delete the absolute and relative position and messages in the infobar
  4895. self.ui.position_label.setText("")
  4896. self.ui.rel_position_label.setText("")
  4897. # Switch plot_area to preferences page
  4898. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4899. self.ui.show()
  4900. def on_select_tab(self, name):
  4901. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4902. if self.ui.splitter.sizes()[0] == 0:
  4903. self.ui.splitter.setSizes([1, 1])
  4904. else:
  4905. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4906. self.ui.splitter.setSizes([0, 1])
  4907. if name == 'project':
  4908. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4909. elif name == 'selected':
  4910. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4911. elif name == 'tool':
  4912. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4913. def on_copy_name(self):
  4914. self.report_usage("on_copy_name()")
  4915. obj = self.collection.get_active()
  4916. try:
  4917. name = obj.options["name"]
  4918. except AttributeError:
  4919. log.debug("on_copy_name() --> No object selected to copy it's name")
  4920. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4921. return
  4922. self.clipboard.setText(name)
  4923. self.inform.emit(_("Name copied on clipboard ..."))
  4924. def on_mouse_click_over_plot(self, event):
  4925. """
  4926. Default actions are:
  4927. :param event: Contains information about the event, like which button
  4928. was clicked, the pixel coordinates and the axes coordinates.
  4929. :return: None
  4930. """
  4931. self.pos = []
  4932. # So it can receive key presses
  4933. self.plotcanvas.vispy_canvas.native.setFocus()
  4934. # Set the mouse button for panning
  4935. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  4936. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4937. if self.grid_status() == True:
  4938. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4939. self.app_cursor.enabled = True
  4940. else:
  4941. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4942. self.app_cursor.enabled = False
  4943. try:
  4944. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4945. if event.button == 1:
  4946. # Reset here the relative coordinates so there is a new reference on the click position
  4947. if self.rel_point1 is None:
  4948. self.rel_point1 = self.pos
  4949. else:
  4950. self.rel_point2 = copy(self.rel_point1)
  4951. self.rel_point1 = self.pos
  4952. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4953. if modifiers == QtCore.Qt.ShiftModifier:
  4954. # do not auto open the Project Tab
  4955. self.click_noproject = True
  4956. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  4957. self.inform.emit(_("[success] Coordinates copied to clipboard."))
  4958. return
  4959. self.on_mouse_move_over_plot(event, origin_click=True)
  4960. except Exception as e:
  4961. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4962. def on_double_click_over_plot(self, event):
  4963. self.doubleclick = True
  4964. def on_mouse_move_over_plot(self, event, origin_click=None):
  4965. """
  4966. Callback for the mouse motion event over the plot.
  4967. :param event: Contains information about the event.
  4968. :param origin_click
  4969. :return: None
  4970. """
  4971. # So it can receive key presses
  4972. self.plotcanvas.vispy_canvas.native.setFocus()
  4973. self.pos_jump = event.pos
  4974. self.ui.popMenu.mouse_is_panning = False
  4975. if origin_click != True:
  4976. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4977. if event.button == 2 and event.is_dragging == 1:
  4978. self.ui.popMenu.mouse_is_panning = True
  4979. return
  4980. if self.rel_point1 is not None:
  4981. try: # May fail in case mouse not within axes
  4982. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4983. if self.grid_status() == True:
  4984. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4985. self.app_cursor.enabled = True
  4986. # Update cursor
  4987. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  4988. else:
  4989. pos = (pos_canvas[0], pos_canvas[1])
  4990. self.app_cursor.enabled = False
  4991. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4992. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  4993. dx = pos[0] - self.rel_point1[0]
  4994. dy = pos[1] - self.rel_point1[1]
  4995. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4996. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4997. self.mouse = [pos[0], pos[1]]
  4998. # if the mouse is moved and the LMB is clicked then the action is a selection
  4999. if event.is_dragging == 1 and event.button == 1:
  5000. self.delete_selection_shape()
  5001. if dx < 0:
  5002. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5003. face_color=self.defaults['global_alt_sel_fill'])
  5004. self.selection_type = False
  5005. else:
  5006. self.draw_moving_selection_shape(self.pos, pos)
  5007. self.selection_type = True
  5008. # hover effect - enabled in Preferences -> General -> GUI Settings
  5009. if self.defaults['global_hover']:
  5010. for obj in self.collection.get_list():
  5011. try:
  5012. # select the object(s) only if it is enabled (plotted)
  5013. if obj.options['plot']:
  5014. if obj not in self.collection.get_selected():
  5015. poly_obj = Polygon(
  5016. [(obj.options['xmin'], obj.options['ymin']),
  5017. (obj.options['xmax'], obj.options['ymin']),
  5018. (obj.options['xmax'], obj.options['ymax']),
  5019. (obj.options['xmin'], obj.options['ymax'])]
  5020. )
  5021. if Point(pos).within(poly_obj):
  5022. if obj.isHovering is False:
  5023. obj.isHovering = True
  5024. obj.notHovering = True
  5025. # create the selection box around the selected object
  5026. self.draw_hover_shape(obj, color='#d1e0e0')
  5027. else:
  5028. if obj.notHovering is True:
  5029. obj.notHovering = False
  5030. obj.isHovering = False
  5031. self.delete_hover_shape()
  5032. except:
  5033. # the Exception here will happen if we try to select on screen and we have an
  5034. # newly (and empty) just created Geometry or Excellon object that do not have the
  5035. # xmin, xmax, ymin, ymax options.
  5036. # In this case poly_obj creation (see above) will fail
  5037. pass
  5038. except:
  5039. self.ui.position_label.setText("")
  5040. self.ui.rel_position_label.setText("")
  5041. self.mouse = None
  5042. def on_mouse_click_release_over_plot(self, event):
  5043. """
  5044. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5045. and has been registered in ''self.__init__()''.
  5046. :param event: contains information about the event.
  5047. :return:
  5048. """
  5049. pos = 0, 0
  5050. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  5051. if self.grid_status() == True:
  5052. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5053. else:
  5054. pos = (pos_canvas[0], pos_canvas[1])
  5055. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5056. # canvas menu
  5057. if event.button == 2: # right click
  5058. if self.ui.popMenu.mouse_is_panning is False:
  5059. self.cursor = QtGui.QCursor()
  5060. self.populate_cmenu_grids()
  5061. self.ui.popMenu.popup(self.cursor.pos())
  5062. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5063. # selection and then select a type of selection ("enclosing" or "touching")
  5064. try:
  5065. if event.button == 1: # left click
  5066. if self.doubleclick is True:
  5067. self.doubleclick = False
  5068. if self.collection.get_selected():
  5069. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5070. if self.ui.splitter.sizes()[0] == 0:
  5071. self.ui.splitter.setSizes([1, 1])
  5072. # delete the selection shape(S) as it may be in the way
  5073. self.delete_selection_shape()
  5074. self.delete_hover_shape()
  5075. else:
  5076. if self.selection_type is not None:
  5077. self.selection_area_handler(self.pos, pos, self.selection_type)
  5078. self.selection_type = None
  5079. else:
  5080. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5081. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5082. # deselect, and if it's not selected then it will be selected
  5083. if modifiers == QtCore.Qt.ControlModifier:
  5084. # If there is no active command (self.command_active is None) then we check if we clicked
  5085. # on a object by checking the bounding limits against mouse click position
  5086. if self.command_active is None:
  5087. self.select_objects(key='CTRL')
  5088. self.delete_hover_shape()
  5089. elif modifiers == QtCore.Qt.ShiftModifier:
  5090. # if SHIFT was pressed and LMB is clicked then we have a coordinates copy to clipboard
  5091. # therefore things should stay as they are
  5092. pass
  5093. else:
  5094. # If there is no active command (self.command_active is None) then we check if we clicked
  5095. # on a object by checking the bounding limits against mouse click position
  5096. if self.command_active is None:
  5097. self.select_objects()
  5098. self.delete_hover_shape()
  5099. except Exception as e:
  5100. log.warning("Error: %s" % str(e))
  5101. return
  5102. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5103. """
  5104. :param start_pos: mouse position when the selection LMB click was done
  5105. :param end_pos: mouse position when the left mouse button is released
  5106. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5107. :return:
  5108. """
  5109. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5110. self.delete_selection_shape()
  5111. for obj in self.collection.get_list():
  5112. try:
  5113. # select the object(s) only if it is enabled (plotted)
  5114. if obj.options['plot']:
  5115. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5116. (obj.options['xmax'], obj.options['ymin']),
  5117. (obj.options['xmax'], obj.options['ymax']),
  5118. (obj.options['xmin'], obj.options['ymax'])])
  5119. if sel_type is True:
  5120. if poly_obj.within(poly_selection):
  5121. # create the selection box around the selected object
  5122. if self.defaults['global_selection_shape'] is True:
  5123. self.draw_selection_shape(obj)
  5124. self.collection.set_active(obj.options['name'])
  5125. else:
  5126. if poly_selection.intersects(poly_obj):
  5127. # create the selection box around the selected object
  5128. if self.defaults['global_selection_shape'] is True:
  5129. self.draw_selection_shape(obj)
  5130. self.collection.set_active(obj.options['name'])
  5131. except Exception as e:
  5132. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5133. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5134. # In this case poly_obj creation (see above) will fail
  5135. log.debug("App.selection_area_handler() --> %s" % str(e))
  5136. def select_objects(self, key=None):
  5137. # list where we store the overlapped objects under our mouse left click position
  5138. objects_under_the_click_list = []
  5139. # Populate the list with the overlapped objects on the click position
  5140. curr_x, curr_y = self.pos
  5141. for obj in self.all_objects_list:
  5142. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5143. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5144. if obj.options['name'] not in objects_under_the_click_list:
  5145. if obj.options['plot']:
  5146. # add objects to the objects_under_the_click list only if the object is plotted
  5147. # (active and not disabled)
  5148. objects_under_the_click_list.append(obj.options['name'])
  5149. try:
  5150. # If there is no element in the overlapped objects list then make everyone inactive
  5151. # because we selected "nothing"
  5152. if not objects_under_the_click_list:
  5153. self.collection.set_all_inactive()
  5154. # delete the possible selection box around a possible selected object
  5155. self.delete_selection_shape()
  5156. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5157. # only when working on App
  5158. if self.call_source == 'app':
  5159. if self.click_noproject is False:
  5160. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5161. else:
  5162. # restore auto open the Project Tab
  5163. self.click_noproject = False
  5164. # delete any text in the status bar, implicitly the last object name that was selected
  5165. self.inform.emit("")
  5166. else:
  5167. self.call_source = 'app'
  5168. else:
  5169. # case when there is only an object under the click and we toggle it
  5170. if len(objects_under_the_click_list) == 1:
  5171. if self.collection.get_active() is None:
  5172. self.collection.set_active(objects_under_the_click_list[0])
  5173. # create the selection box around the selected object
  5174. curr_sel_obj = self.collection.get_active()
  5175. if self.defaults['global_selection_shape'] is True:
  5176. self.draw_selection_shape(curr_sel_obj)
  5177. # self.inform.emit('[selected] %s: %s selected' %
  5178. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5179. if curr_sel_obj.kind == 'gerber':
  5180. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5181. color='green', name=str(curr_sel_obj.options['name'])))
  5182. elif curr_sel_obj.kind == 'excellon':
  5183. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5184. color='brown', name=str(curr_sel_obj.options['name'])))
  5185. elif curr_sel_obj.kind == 'cncjob':
  5186. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5187. color='blue', name=str(curr_sel_obj.options['name'])))
  5188. elif curr_sel_obj.kind == 'geometry':
  5189. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5190. color='red', name=str(curr_sel_obj.options['name'])))
  5191. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  5192. self.collection.set_all_inactive()
  5193. self.delete_selection_shape()
  5194. self.collection.set_active(objects_under_the_click_list[0])
  5195. # create the selection box around the selected object
  5196. curr_sel_obj = self.collection.get_active()
  5197. if self.defaults['global_selection_shape'] is True:
  5198. self.draw_selection_shape(curr_sel_obj)
  5199. # self.inform.emit('[selected] %s: %s selected' %
  5200. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5201. if curr_sel_obj.kind == 'gerber':
  5202. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5203. color='green', name=str(curr_sel_obj.options['name'])))
  5204. elif curr_sel_obj.kind == 'excellon':
  5205. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5206. color='brown', name=str(curr_sel_obj.options['name'])))
  5207. elif curr_sel_obj.kind == 'cncjob':
  5208. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5209. color='blue', name=str(curr_sel_obj.options['name'])))
  5210. elif curr_sel_obj.kind == 'geometry':
  5211. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5212. color='red', name=str(curr_sel_obj.options['name'])))
  5213. else:
  5214. self.collection.set_all_inactive()
  5215. self.delete_selection_shape()
  5216. if self.call_source == 'app':
  5217. # delete any text in the status bar, implicitly the last object name that was selected
  5218. self.inform.emit("")
  5219. else:
  5220. self.call_source = 'app'
  5221. else:
  5222. # If there is no selected object
  5223. # make active the first element of the overlapped objects list
  5224. if self.collection.get_active() is None:
  5225. self.collection.set_active(objects_under_the_click_list[0])
  5226. name_sel_obj = self.collection.get_active().options['name']
  5227. # In case that there is a selected object but it is not in the overlapped object list
  5228. # make that object inactive and activate the first element in the overlapped object list
  5229. if name_sel_obj not in objects_under_the_click_list:
  5230. self.collection.set_inactive(name_sel_obj)
  5231. name_sel_obj = objects_under_the_click_list[0]
  5232. self.collection.set_active(name_sel_obj)
  5233. else:
  5234. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  5235. self.collection.set_all_inactive()
  5236. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  5237. len(objects_under_the_click_list)])
  5238. curr_sel_obj = self.collection.get_active()
  5239. # delete the possible selection box around a possible selected object
  5240. self.delete_selection_shape()
  5241. # create the selection box around the selected object
  5242. if self.defaults['global_selection_shape'] is True:
  5243. self.draw_selection_shape(curr_sel_obj)
  5244. # self.inform.emit('[selected] %s: %s selected' %
  5245. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  5246. if curr_sel_obj.kind == 'gerber':
  5247. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5248. color='green', name=str(curr_sel_obj.options['name'])))
  5249. elif curr_sel_obj.kind == 'excellon':
  5250. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5251. color='brown', name=str(curr_sel_obj.options['name'])))
  5252. elif curr_sel_obj.kind == 'cncjob':
  5253. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5254. color='blue', name=str(curr_sel_obj.options['name'])))
  5255. elif curr_sel_obj.kind == 'geometry':
  5256. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  5257. color='red', name=str(curr_sel_obj.options['name'])))
  5258. # for obj in self.collection.get_list():
  5259. # obj.plot()
  5260. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  5261. # TODO: on selected objects change the object colors and do not draw the selection box
  5262. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  5263. except Exception as e:
  5264. log.error("[ERROR] Something went bad. %s" % str(e))
  5265. return
  5266. def delete_hover_shape(self):
  5267. self.hover_shapes.clear()
  5268. self.hover_shapes.redraw()
  5269. def draw_hover_shape(self, sel_obj, color=None):
  5270. """
  5271. :param sel_obj: the object for which the hover shape must be drawn
  5272. :return:
  5273. """
  5274. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5275. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5276. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5277. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5278. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5279. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5280. hover_rect = hover_rect.buffer(-0.1)
  5281. hover_rect = hover_rect.buffer(0.2)
  5282. else:
  5283. hover_rect = hover_rect.buffer(-0.00393)
  5284. hover_rect = hover_rect.buffer(0.00787)
  5285. if color:
  5286. face = Color(color)
  5287. face.alpha = 0.2
  5288. outline = Color(color, alpha=0.8)
  5289. else:
  5290. face = Color(self.defaults['global_sel_fill'])
  5291. face.alpha = 0.2
  5292. outline = self.defaults['global_sel_line']
  5293. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5294. def delete_selection_shape(self):
  5295. self.move_tool.sel_shapes.clear()
  5296. self.move_tool.sel_shapes.redraw()
  5297. def draw_selection_shape(self, sel_obj, color=None):
  5298. """
  5299. :param sel_obj: the object for which the selection shape must be drawn
  5300. :return:
  5301. """
  5302. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5303. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5304. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5305. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5306. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5307. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  5308. sel_rect = sel_rect.buffer(-0.1)
  5309. sel_rect = sel_rect.buffer(0.2)
  5310. else:
  5311. sel_rect = sel_rect.buffer(-0.00393)
  5312. sel_rect = sel_rect.buffer(0.00787)
  5313. if color:
  5314. face = Color(color, alpha=0.2)
  5315. outline = Color(color, alpha=0.8)
  5316. else:
  5317. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  5318. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  5319. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5320. color=outline,
  5321. face_color=face,
  5322. update=True,
  5323. layer=0,
  5324. tolerance=None))
  5325. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5326. """
  5327. :param old_coords: old coordinates
  5328. :param coords: new coordinates
  5329. :return:
  5330. """
  5331. if 'color' in kwargs:
  5332. color = kwargs['color']
  5333. else:
  5334. color = self.defaults['global_sel_line']
  5335. if 'face_color' in kwargs:
  5336. face_color = kwargs['face_color']
  5337. else:
  5338. face_color = self.defaults['global_sel_fill']
  5339. if 'face_alpha' in kwargs:
  5340. face_alpha = kwargs['face_alpha']
  5341. else:
  5342. face_alpha = 0.3
  5343. x0, y0 = old_coords
  5344. x1, y1 = coords
  5345. pt1 = (x0, y0)
  5346. pt2 = (x1, y0)
  5347. pt3 = (x1, y1)
  5348. pt4 = (x0, y1)
  5349. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5350. color_t = Color(face_color)
  5351. color_t.alpha = face_alpha
  5352. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5353. layer=0, tolerance=None)
  5354. def on_file_new_click(self):
  5355. if self.collection.get_list() and self.should_we_save:
  5356. msgbox = QtWidgets.QMessageBox()
  5357. # msgbox.setText("<B>Save changes ...</B>")
  5358. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5359. "Creating a New project will delete them.\n"
  5360. "Do you want to Save the project?"))
  5361. msgbox.setWindowTitle(_("Save changes"))
  5362. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5363. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5364. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5365. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5366. msgbox.setDefaultButton(bt_yes)
  5367. msgbox.exec_()
  5368. response = msgbox.clickedButton()
  5369. if response == bt_yes:
  5370. self.on_file_saveprojectas()
  5371. elif response == bt_cancel:
  5372. return
  5373. elif response == bt_no:
  5374. self.on_file_new()
  5375. else:
  5376. self.on_file_new()
  5377. self.inform.emit(_("[success] New Project created..."))
  5378. def on_file_new(self):
  5379. """
  5380. Callback for menu item File->New. Returns the application to its
  5381. startup state. This method is thread-safe.
  5382. :return: None
  5383. """
  5384. self.report_usage("on_file_new")
  5385. # Remove everything from memory
  5386. App.log.debug("on_file_new()")
  5387. if self.call_source != 'app':
  5388. self.editor2object(cleanup=True)
  5389. # ## EDITOR section
  5390. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  5391. self.exc_editor = FlatCAMExcEditor(self)
  5392. self.grb_editor = FlatCAMGrbEditor(self)
  5393. # Clear pool
  5394. self.clear_pool()
  5395. for obj in self.collection.get_list():
  5396. # delete shapes left drawn from mark shape_collections, if any
  5397. if isinstance(obj, FlatCAMGerber):
  5398. try:
  5399. obj.mark_shapes.enabled = False
  5400. obj.mark_shapes.clear(update=True)
  5401. except AttributeError:
  5402. pass
  5403. # also delete annotation shapes, if any
  5404. elif isinstance(obj, FlatCAMCNCjob):
  5405. try:
  5406. obj.annotation.enabled = False
  5407. obj.annotation.clear(update=True)
  5408. except AttributeError:
  5409. pass
  5410. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5411. self.init_tcl()
  5412. self.delete_selection_shape()
  5413. self.collection.delete_all()
  5414. self.setup_component_editor()
  5415. # Clear project filename
  5416. self.project_filename = None
  5417. # Load the application defaults
  5418. self.load_defaults(filename='current_defaults')
  5419. # Re-fresh project options
  5420. self.on_options_app2project()
  5421. # Init Tools
  5422. self.init_tools()
  5423. # Close any Tabs opened in the Plot Tab Area section
  5424. for index in range(self.ui.plot_tab_area.count()):
  5425. self.ui.plot_tab_area.closeTab(index)
  5426. # for whatever reason previous command does not close the last tab so I do it manually
  5427. self.ui.plot_tab_area.closeTab(0)
  5428. # # And then add again the Plot Area
  5429. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5430. self.ui.plot_tab_area.protectTab(0)
  5431. # take the focus of the Notebook on Project Tab.
  5432. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5433. self.set_ui_title(name=_("New Project - Not saved"))
  5434. def obj_properties(self):
  5435. self.report_usage("obj_properties()")
  5436. self.properties_tool.run(toggle=False)
  5437. def on_project_context_save(self):
  5438. obj = self.collection.get_active()
  5439. if type(obj) == FlatCAMGeometry:
  5440. self.on_file_exportdxf()
  5441. elif type(obj) == FlatCAMExcellon:
  5442. self.on_file_saveexcellon()
  5443. elif type(obj) == FlatCAMCNCjob:
  5444. obj.on_exportgcode_button_click()
  5445. elif type(obj) == FlatCAMGerber:
  5446. self.on_file_savegerber()
  5447. def obj_move(self):
  5448. self.report_usage("obj_move()")
  5449. self.move_tool.run(toggle=False)
  5450. def on_fileopengerber(self):
  5451. """
  5452. File menu callback for opening a Gerber.
  5453. :return: None
  5454. """
  5455. self.report_usage("on_fileopengerber")
  5456. App.log.debug("on_fileopengerber()")
  5457. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5458. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5459. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  5460. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5461. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5462. "*.mil);;" \
  5463. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5464. "Allegro Files (*.art);;" \
  5465. "Mentor Files (*.pho *.gdo);;" \
  5466. "All Files (*.*)"
  5467. try:
  5468. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5469. directory=self.get_last_folder(), filter=_filter_)
  5470. except TypeError:
  5471. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5472. filenames = [str(filename) for filename in filenames]
  5473. if len(filenames) == 0:
  5474. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  5475. else:
  5476. for filename in filenames:
  5477. if filename != '':
  5478. self.worker_task.emit({'fcn': self.open_gerber,
  5479. 'params': [filename]})
  5480. def on_fileopenexcellon(self):
  5481. """
  5482. File menu callback for opening an Excellon file.
  5483. :return: None
  5484. """
  5485. self.report_usage("on_fileopenexcellon")
  5486. App.log.debug("on_fileopenexcellon()")
  5487. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5488. "All Files (*.*)"
  5489. try:
  5490. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5491. directory=self.get_last_folder(), filter=_filter_)
  5492. except TypeError:
  5493. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5494. filenames = [str(filename) for filename in filenames]
  5495. if len(filenames) == 0:
  5496. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  5497. else:
  5498. for filename in filenames:
  5499. if filename != '':
  5500. self.worker_task.emit({'fcn': self.open_excellon,
  5501. 'params': [filename]})
  5502. def on_fileopengcode(self):
  5503. """
  5504. File menu call back for opening gcode.
  5505. :return: None
  5506. """
  5507. self.report_usage("on_fileopengcode")
  5508. App.log.debug("on_fileopengcode()")
  5509. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5510. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5511. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  5512. "All Files (*.*)"
  5513. try:
  5514. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5515. directory=self.get_last_folder(), filter=_filter_)
  5516. except TypeError:
  5517. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5518. filenames = [str(filename) for filename in filenames]
  5519. if len(filenames) == 0:
  5520. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  5521. else:
  5522. for filename in filenames:
  5523. if filename != '':
  5524. self.worker_task.emit({'fcn': self.open_gcode,
  5525. 'params': [filename]})
  5526. def on_file_openproject(self):
  5527. """
  5528. File menu callback for opening a project.
  5529. :return: None
  5530. """
  5531. self.report_usage("on_file_openproject")
  5532. App.log.debug("on_file_openproject()")
  5533. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5534. try:
  5535. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5536. directory=self.get_last_folder(), filter=_filter_)
  5537. except TypeError:
  5538. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5539. # The Qt methods above will return a QString which can cause problems later.
  5540. # So far json.dump() will fail to serialize it.
  5541. # TODO: Improve the serialization methods and remove this fix.
  5542. filename = str(filename)
  5543. if filename == "":
  5544. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  5545. else:
  5546. # self.worker_task.emit({'fcn': self.open_project,
  5547. # 'params': [filename]})
  5548. # The above was failing because open_project() is not
  5549. # thread safe. The new_project()
  5550. self.open_project(filename)
  5551. def on_file_openconfig(self):
  5552. """
  5553. File menu callback for opening a config file.
  5554. :return: None
  5555. """
  5556. self.report_usage("on_file_openconfig")
  5557. App.log.debug("on_file_openconfig()")
  5558. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5559. try:
  5560. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5561. directory=self.data_path, filter=_filter_)
  5562. except TypeError:
  5563. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5564. filter=_filter_)
  5565. if filename == "":
  5566. self.inform.emit(_("[WARNING_NOTCL] Open Config cancelled."))
  5567. else:
  5568. self.open_config_file(filename)
  5569. def on_file_exportsvg(self):
  5570. """
  5571. Callback for menu item File->Export SVG.
  5572. :return: None
  5573. """
  5574. self.report_usage("on_file_exportsvg")
  5575. App.log.debug("on_file_exportsvg()")
  5576. obj = self.collection.get_active()
  5577. if obj is None:
  5578. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5579. msg = _("Please Select a Geometry object to export")
  5580. msgbox = QtWidgets.QMessageBox()
  5581. msgbox.setInformativeText(msg)
  5582. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5583. msgbox.setDefaultButton(bt_ok)
  5584. msgbox.exec_()
  5585. return
  5586. # Check for more compatible types and add as required
  5587. if (not isinstance(obj, FlatCAMGeometry)
  5588. and not isinstance(obj, FlatCAMGerber)
  5589. and not isinstance(obj, FlatCAMCNCjob)
  5590. and not isinstance(obj, FlatCAMExcellon)):
  5591. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  5592. msgbox = QtWidgets.QMessageBox()
  5593. msgbox.setInformativeText(msg)
  5594. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5595. msgbox.setDefaultButton(bt_ok)
  5596. msgbox.exec_()
  5597. return
  5598. name = obj.options["name"]
  5599. _filter = "SVG File (*.svg);;All Files (*.*)"
  5600. try:
  5601. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5602. caption=_("Export SVG"),
  5603. directory=self.get_last_save_folder() + '/' + str(name),
  5604. filter=_filter)
  5605. except TypeError:
  5606. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  5607. filename = str(filename)
  5608. if filename == "":
  5609. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  5610. return
  5611. else:
  5612. self.export_svg(name, filename)
  5613. if self.defaults["global_open_style"] is False:
  5614. self.file_opened.emit("SVG", filename)
  5615. self.file_saved.emit("SVG", filename)
  5616. def on_file_exportpng(self):
  5617. self.report_usage("on_file_exportpng")
  5618. App.log.debug("on_file_exportpng()")
  5619. self.date = str(datetime.today()).rpartition('.')[0]
  5620. self.date = ''.join(c for c in self.date if c not in ':-')
  5621. self.date = self.date.replace(' ', '_')
  5622. image = _screenshot()
  5623. data = np.asarray(image)
  5624. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5625. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  5626. return
  5627. filter_ = "PNG File (*.png);;All Files (*.*)"
  5628. try:
  5629. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5630. caption=_("Export PNG Image"),
  5631. directory=self.get_last_save_folder() + '/png_' + self.date,
  5632. filter=filter_)
  5633. except TypeError:
  5634. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  5635. filename = str(filename)
  5636. if filename == "":
  5637. self.inform.emit(_("Export PNG cancelled."))
  5638. return
  5639. else:
  5640. write_png(filename, data)
  5641. if self.defaults["global_open_style"] is False:
  5642. self.file_opened.emit("png", filename)
  5643. self.file_saved.emit("png", filename)
  5644. def on_file_savegerber(self):
  5645. """
  5646. Callback for menu item File->Export Gerber.
  5647. :return: None
  5648. """
  5649. self.report_usage("on_file_savegerber")
  5650. App.log.debug("on_file_savegerber()")
  5651. obj = self.collection.get_active()
  5652. if obj is None:
  5653. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  5654. return
  5655. # Check for more compatible types and add as required
  5656. if not isinstance(obj, FlatCAMGerber):
  5657. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5658. return
  5659. name = self.collection.get_active().options["name"]
  5660. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5661. try:
  5662. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5663. caption="Save Gerber source file",
  5664. directory=self.get_last_save_folder() + '/' + name,
  5665. filter=_filter)
  5666. except TypeError:
  5667. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  5668. filename = str(filename)
  5669. if filename == "":
  5670. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  5671. return
  5672. else:
  5673. self.save_source_file(name, filename)
  5674. if self.defaults["global_open_style"] is False:
  5675. self.file_opened.emit("Gerber", filename)
  5676. self.file_saved.emit("Gerber", filename)
  5677. def on_file_saveexcellon(self):
  5678. """
  5679. Callback for menu item File->Export Gerber.
  5680. :return: None
  5681. """
  5682. self.report_usage("on_file_saveexcellon")
  5683. App.log.debug("on_file_saveexcellon()")
  5684. obj = self.collection.get_active()
  5685. if obj is None:
  5686. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  5687. return
  5688. # Check for more compatible types and add as required
  5689. if not isinstance(obj, FlatCAMExcellon):
  5690. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5691. return
  5692. name = self.collection.get_active().options["name"]
  5693. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5694. try:
  5695. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5696. caption=_("Save Excellon source file"),
  5697. directory=self.get_last_save_folder() + '/' + name,
  5698. filter=_filter)
  5699. except TypeError:
  5700. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  5701. filename = str(filename)
  5702. if filename == "":
  5703. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  5704. return
  5705. else:
  5706. self.save_source_file(name, filename)
  5707. if self.defaults["global_open_style"] is False:
  5708. self.file_opened.emit("Excellon", filename)
  5709. self.file_saved.emit("Excellon", filename)
  5710. def on_file_exportexcellon(self):
  5711. """
  5712. Callback for menu item File->Export->Excellon.
  5713. :return: None
  5714. """
  5715. self.report_usage("on_file_exportexcellon")
  5716. App.log.debug("on_file_exportexcellon()")
  5717. obj = self.collection.get_active()
  5718. if obj is None:
  5719. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  5720. return
  5721. # Check for more compatible types and add as required
  5722. if not isinstance(obj, FlatCAMExcellon):
  5723. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5724. return
  5725. name = self.collection.get_active().options["name"]
  5726. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5727. try:
  5728. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5729. caption=_("Export Excellon"),
  5730. directory=self.get_last_save_folder() + '/' + name,
  5731. filter=_filter)
  5732. except TypeError:
  5733. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  5734. filename = str(filename)
  5735. if filename == "":
  5736. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  5737. return
  5738. else:
  5739. self.export_excellon(name, filename)
  5740. if self.defaults["global_open_style"] is False:
  5741. self.file_opened.emit("Excellon", filename)
  5742. self.file_saved.emit("Excellon", filename)
  5743. def on_file_exportgerber(self):
  5744. """
  5745. Callback for menu item File->Export->Gerber.
  5746. :return: None
  5747. """
  5748. self.report_usage("on_file_exportgerber")
  5749. App.log.debug("on_file_exportgerber()")
  5750. obj = self.collection.get_active()
  5751. if obj is None:
  5752. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export."))
  5753. return
  5754. # Check for more compatible types and add as required
  5755. if not isinstance(obj, FlatCAMGerber):
  5756. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5757. return
  5758. name = self.collection.get_active().options["name"]
  5759. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  5760. try:
  5761. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5762. caption=_("Export Gerber"),
  5763. directory=self.get_last_save_folder() + '/' + name,
  5764. filter=_filter_)
  5765. except TypeError:
  5766. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  5767. filename = str(filename)
  5768. if filename == "":
  5769. self.inform.emit(_("[WARNING_NOTCL] Export Gerber cancelled."))
  5770. return
  5771. else:
  5772. self.export_gerber(name, filename)
  5773. if self.defaults["global_open_style"] is False:
  5774. self.file_opened.emit("Gerber", filename)
  5775. self.file_saved.emit("Gerber", filename)
  5776. def on_file_exportdxf(self):
  5777. """
  5778. Callback for menu item File->Export DXF.
  5779. :return: None
  5780. """
  5781. self.report_usage("on_file_exportdxf")
  5782. App.log.debug("on_file_exportdxf()")
  5783. obj = self.collection.get_active()
  5784. if obj is None:
  5785. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5786. msg = _("Please Select a Geometry object to export")
  5787. msgbox = QtWidgets.QMessageBox()
  5788. msgbox.setInformativeText(msg)
  5789. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5790. msgbox.setDefaultButton(bt_ok)
  5791. msgbox.exec_()
  5792. return
  5793. # Check for more compatible types and add as required
  5794. if not isinstance(obj, FlatCAMGeometry):
  5795. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  5796. msgbox = QtWidgets.QMessageBox()
  5797. msgbox.setInformativeText(msg)
  5798. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5799. msgbox.setDefaultButton(bt_ok)
  5800. msgbox.exec_()
  5801. return
  5802. name = self.collection.get_active().options["name"]
  5803. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5804. try:
  5805. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5806. caption=_("Export DXF"),
  5807. directory=self.get_last_save_folder() + '/' + name,
  5808. filter=_filter_)
  5809. except TypeError:
  5810. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  5811. filter=_filter_)
  5812. filename = str(filename)
  5813. if filename == "":
  5814. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  5815. return
  5816. else:
  5817. self.export_dxf(name, filename)
  5818. if self.defaults["global_open_style"] is False:
  5819. self.file_opened.emit("DXF", filename)
  5820. self.file_saved.emit("DXF", filename)
  5821. def on_file_importsvg(self, type_of_obj):
  5822. """
  5823. Callback for menu item File->Import SVG.
  5824. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5825. :type type_of_obj: str
  5826. :return: None
  5827. """
  5828. self.report_usage("on_file_importsvg")
  5829. App.log.debug("on_file_importsvg()")
  5830. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  5831. try:
  5832. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5833. directory=self.get_last_folder(), filter=_filter_)
  5834. except TypeError:
  5835. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5836. filter=_filter_)
  5837. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5838. type_of_obj = "geometry"
  5839. filenames = [str(filename) for filename in filenames]
  5840. if len(filenames) == 0:
  5841. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  5842. else:
  5843. for filename in filenames:
  5844. if filename != '':
  5845. self.worker_task.emit({'fcn': self.import_svg,
  5846. 'params': [filename, type_of_obj]})
  5847. def on_file_importdxf(self, type_of_obj):
  5848. """
  5849. Callback for menu item File->Import DXF.
  5850. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5851. :type type_of_obj: str
  5852. :return: None
  5853. """
  5854. self.report_usage("on_file_importdxf")
  5855. App.log.debug("on_file_importdxf()")
  5856. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5857. try:
  5858. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5859. directory=self.get_last_folder(),
  5860. filter=_filter_)
  5861. except TypeError:
  5862. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5863. filter=_filter_)
  5864. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5865. type_of_obj = "geometry"
  5866. filenames = [str(filename) for filename in filenames]
  5867. if len(filenames) == 0:
  5868. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  5869. else:
  5870. for filename in filenames:
  5871. if filename != '':
  5872. self.worker_task.emit({'fcn': self.import_dxf,
  5873. 'params': [filename, type_of_obj]})
  5874. # ###############################################################################################################
  5875. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5876. # ###############################################################################################################
  5877. def init_code_editor(self, name):
  5878. # Signals section
  5879. # Disconnect the old signals
  5880. self.ui.buttonOpen.clicked.disconnect()
  5881. self.ui.buttonSave.clicked.disconnect()
  5882. # add the tab if it was closed
  5883. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  5884. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  5885. # delete the absolute and relative position and messages in the infobar
  5886. self.ui.position_label.setText("")
  5887. self.ui.rel_position_label.setText("")
  5888. # first clear previous text in text editor (if any)
  5889. self.ui.code_editor.clear()
  5890. self.ui.code_editor.setReadOnly(False)
  5891. self.toggle_codeeditor = True
  5892. self.ui.code_editor.completer_enable = False
  5893. # Switch plot_area to CNCJob tab
  5894. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5895. def on_view_source(self):
  5896. try:
  5897. obj = self.collection.get_active()
  5898. except:
  5899. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5900. return 'fail'
  5901. # then append the text from GCode to the text editor
  5902. try:
  5903. file = StringIO(obj.source_file)
  5904. except AttributeError:
  5905. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5906. return 'fail'
  5907. if obj.kind == 'gerber':
  5908. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5909. elif obj.kind == 'excellon':
  5910. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5911. self.init_code_editor(name=_("Source Editor"))
  5912. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5913. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5914. try:
  5915. for line in file:
  5916. proc_line = str(line).strip('\n')
  5917. self.ui.code_editor.append(proc_line)
  5918. except Exception as e:
  5919. log.debug('App.on_view_source() -->%s' % str(e))
  5920. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5921. return
  5922. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5923. self.handleTextChanged()
  5924. self.ui.show()
  5925. def on_toggle_code_editor(self):
  5926. self.report_usage("on_toggle_code_editor()")
  5927. if self.toggle_codeeditor is False:
  5928. self.init_code_editor(name=_("Code Editor"))
  5929. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  5930. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  5931. else:
  5932. for idx in range(self.ui.plot_tab_area.count()):
  5933. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  5934. self.ui.plot_tab_area.closeTab(idx)
  5935. break
  5936. self.toggle_codeeditor = False
  5937. def on_filenewscript(self):
  5938. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5939. self.init_code_editor(name=_("Script Editor"))
  5940. self.ui.code_editor.completer_enable = True
  5941. self.ui.code_editor.append(_(
  5942. "#\n"
  5943. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  5944. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  5945. "#\n\n"
  5946. "# FlatCAM commands list:\n"
  5947. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  5948. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  5949. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  5950. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  5951. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  5952. "# WriteGCode\n"
  5953. "#\n\n"
  5954. ))
  5955. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5956. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5957. self.handleTextChanged()
  5958. self.ui.code_editor.show()
  5959. def on_fileopenscript(self):
  5960. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5961. try:
  5962. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  5963. directory=self.get_last_folder(), filter=_filter_)
  5964. except TypeError:
  5965. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  5966. # The Qt methods above will return a QString which can cause problems later.
  5967. # So far json.dump() will fail to serialize it.
  5968. # TODO: Improve the serialization methods and remove this fix.
  5969. filename = str(filename)
  5970. if filename == "":
  5971. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  5972. else:
  5973. self.on_filenewscript()
  5974. try:
  5975. with open(filename, "r") as opened_script:
  5976. try:
  5977. for line in opened_script:
  5978. proc_line = str(line).strip('\n')
  5979. self.ui.code_editor.append(proc_line)
  5980. except Exception as e:
  5981. log.debug('App.on_fileopenscript() -->%s' % str(e))
  5982. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  5983. return
  5984. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5985. self.handleTextChanged()
  5986. self.ui.show()
  5987. except Exception as e:
  5988. log.debug("App.on_fileopenscript() -> %s" % str(e))
  5989. def on_filerunscript(self, name=None):
  5990. """
  5991. File menu callback for loading and running a TCL script.
  5992. :return: None
  5993. """
  5994. self.report_usage("on_filerunscript")
  5995. App.log.debug("on_file_runscript()")
  5996. if name:
  5997. filename = name
  5998. else:
  5999. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  6000. try:
  6001. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6002. directory=self.get_last_folder(), filter=_filter_)
  6003. except TypeError:
  6004. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6005. # The Qt methods above will return a QString which can cause problems later.
  6006. # So far json.dump() will fail to serialize it.
  6007. # TODO: Improve the serialization methods and remove this fix.
  6008. filename = str(filename)
  6009. if filename == "":
  6010. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  6011. else:
  6012. try:
  6013. with open(filename, "r") as tcl_script:
  6014. cmd_line_shellfile_content = tcl_script.read()
  6015. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  6016. except Exception as e:
  6017. log.debug("App.on_filerunscript() -> %s" % str(e))
  6018. sys.exit(2)
  6019. def on_file_saveproject(self):
  6020. """
  6021. Callback for menu item File->Save Project. Saves the project to
  6022. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6023. if set to None. The project is saved by calling ``self.save_project()``.
  6024. :return: None
  6025. """
  6026. self.report_usage("on_file_saveproject")
  6027. if self.project_filename is None:
  6028. self.on_file_saveprojectas()
  6029. else:
  6030. self.worker_task.emit({'fcn': self.save_project,
  6031. 'params': [self.project_filename]})
  6032. if self.defaults["global_open_style"] is False:
  6033. self.file_opened.emit("project", self.project_filename)
  6034. self.file_saved.emit("project", self.project_filename)
  6035. self.set_ui_title(name=self.project_filename)
  6036. self.should_we_save = False
  6037. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6038. """
  6039. Callback for menu item File->Save Project As... Opens a file
  6040. chooser and saves the project to the given file via
  6041. ``self.save_project()``.
  6042. :param make_copy if to be create a copy of the project; boolean
  6043. :param use_thread: if to be run in a separate thread; boolean
  6044. :param quit_action: if to be followed by quiting the application; boolean
  6045. :return: None
  6046. """
  6047. self.report_usage("on_file_saveprojectas")
  6048. self.date = str(datetime.today()).rpartition('.')[0]
  6049. self.date = ''.join(c for c in self.date if c not in ':-')
  6050. self.date = self.date.replace(' ', '_')
  6051. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  6052. try:
  6053. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6054. caption=_("Save Project As ..."),
  6055. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  6056. filter=filter_)
  6057. except TypeError:
  6058. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  6059. filename = str(filename)
  6060. if filename == '':
  6061. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  6062. return
  6063. try:
  6064. f = open(filename, 'r')
  6065. f.close()
  6066. except IOError:
  6067. pass
  6068. if use_thread is True:
  6069. self.worker_task.emit({'fcn': self.save_project,
  6070. 'params': [filename, quit_action]})
  6071. else:
  6072. self.save_project(filename, quit_action)
  6073. # self.save_project(filename)
  6074. if self.defaults["global_open_style"] is False:
  6075. self.file_opened.emit("project", filename)
  6076. self.file_saved.emit("project", filename)
  6077. if not make_copy:
  6078. self.project_filename = filename
  6079. self.set_ui_title(name=self.project_filename)
  6080. self.should_we_save = False
  6081. def export_svg(self, obj_name, filename, scale_factor=0.00):
  6082. """
  6083. Exports a Geometry Object to an SVG file.
  6084. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6085. :param filename: Path to the SVG file to save to.
  6086. :param scale_factor: factor by which to change/scale the thickness of the features
  6087. :return:
  6088. """
  6089. self.report_usage("export_svg()")
  6090. if filename is None:
  6091. filename = self.defaults["global_last_save_folder"]
  6092. self.log.debug("export_svg()")
  6093. try:
  6094. obj = self.collection.get_by_name(str(obj_name))
  6095. except:
  6096. # TODO: The return behavior has not been established... should raise exception?
  6097. return "Could not retrieve object: %s" % obj_name
  6098. with self.proc_container.new(_("Exporting SVG")) as proc:
  6099. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6100. # Determine bounding area for svg export
  6101. bounds = obj.bounds()
  6102. size = obj.size()
  6103. # Convert everything to strings for use in the xml doc
  6104. svgwidth = str(size[0])
  6105. svgheight = str(size[1])
  6106. minx = str(bounds[0])
  6107. miny = str(bounds[1] - size[1])
  6108. uom = obj.units.lower()
  6109. # Add a SVG Header and footer to the svg output from shapely
  6110. # The transform flips the Y Axis so that everything renders
  6111. # properly within svg apps such as inkscape
  6112. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6113. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6114. svg_header += 'width="' + svgwidth + uom + '" '
  6115. svg_header += 'height="' + svgheight + uom + '" '
  6116. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6117. svg_header += '<g transform="scale(1,-1)">'
  6118. svg_footer = '</g> </svg>'
  6119. svg_elem = svg_header + exported_svg + svg_footer
  6120. # Parse the xml through a xml parser just to add line feeds
  6121. # and to make it look more pretty for the output
  6122. svgcode = parse_xml_string(svg_elem)
  6123. try:
  6124. with open(filename, 'w') as fp:
  6125. fp.write(svgcode.toprettyxml())
  6126. except PermissionError:
  6127. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6128. "Most likely another app is holding the file open and not accessible."))
  6129. return 'fail'
  6130. if self.defaults["global_open_style"] is False:
  6131. self.file_opened.emit("SVG", filename)
  6132. self.file_saved.emit("SVG", filename)
  6133. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6134. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  6135. """
  6136. Exports a Geometry Object to an SVG file in negative.
  6137. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6138. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6139. :param filename: Path to the SVG file to save to.
  6140. :param boundary: thickness of a black border to surround all the features
  6141. :param scale_factor: factor by which to change/scale the thickness of the features
  6142. :param use_thread: if to be run in a separate thread; boolean
  6143. :return:
  6144. """
  6145. self.report_usage("export_negative()")
  6146. if filename is None:
  6147. filename = self.defaults["global_last_save_folder"]
  6148. self.log.debug("export_svg() negative")
  6149. try:
  6150. obj = self.collection.get_by_name(str(obj_name))
  6151. except:
  6152. # TODO: The return behavior has not been established... should raise exception?
  6153. return "Could not retrieve object: %s" % obj_name
  6154. try:
  6155. box = self.collection.get_by_name(str(box_name))
  6156. except:
  6157. # TODO: The return behavior has not been established... should raise exception?
  6158. return "Could not retrieve object: %s" % box_name
  6159. if box is None:
  6160. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  6161. box = obj
  6162. def make_negative_film():
  6163. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6164. self.progress.emit(40)
  6165. # Determine bounding area for svg export
  6166. bounds = box.bounds()
  6167. size = box.size()
  6168. uom = obj.units.lower()
  6169. # Convert everything to strings for use in the xml doc
  6170. svgwidth = str(size[0] + (2 * boundary))
  6171. svgheight = str(size[1] + (2 * boundary))
  6172. minx = str(bounds[0] - boundary)
  6173. miny = str(bounds[1] + boundary + size[1])
  6174. miny_rect = str(bounds[1] - boundary)
  6175. # Add a SVG Header and footer to the svg output from shapely
  6176. # The transform flips the Y Axis so that everything renders
  6177. # properly within svg apps such as inkscape
  6178. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6179. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6180. svg_header += 'width="' + svgwidth + uom + '" '
  6181. svg_header += 'height="' + svgheight + uom + '" '
  6182. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6183. svg_header += '>'
  6184. svg_header += '<g transform="scale(1,-1)">'
  6185. svg_footer = '</g> </svg>'
  6186. self.progress.emit(60)
  6187. # Change the attributes of the exported SVG
  6188. # We don't need stroke-width - wrong, we do when we have lines with certain width
  6189. # We set opacity to maximum
  6190. # We set the color to WHITE
  6191. root = ET.fromstring(exported_svg)
  6192. for child in root:
  6193. child.set('fill', '#FFFFFF')
  6194. child.set('opacity', '1.0')
  6195. child.set('stroke', '#FFFFFF')
  6196. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  6197. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  6198. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  6199. first_svg_elem_tag = 'rect'
  6200. first_svg_elem_attribs = {
  6201. 'x': minx,
  6202. 'y': miny_rect,
  6203. 'width': svgwidth,
  6204. 'height': svgheight,
  6205. 'id': 'neg_rect',
  6206. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  6207. }
  6208. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  6209. exported_svg = ET.tostring(root)
  6210. svg_elem = svg_header + str(exported_svg) + svg_footer
  6211. self.progress.emit(80)
  6212. # Parse the xml through a xml parser just to add line feeds
  6213. # and to make it look more pretty for the output
  6214. doc = parse_xml_string(svg_elem)
  6215. try:
  6216. with open(filename, 'w') as fp:
  6217. fp.write(doc.toprettyxml())
  6218. except PermissionError:
  6219. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6220. "Most likely another app is holding the file open and not accessible."))
  6221. return 'fail'
  6222. self.progress.emit(100)
  6223. if self.defaults["global_open_style"] is False:
  6224. self.file_opened.emit("SVG", filename)
  6225. self.file_saved.emit("SVG", filename)
  6226. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6227. if use_thread is True:
  6228. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6229. def job_thread_film(app_obj):
  6230. try:
  6231. make_negative_film()
  6232. except Exception as e:
  6233. proc.done()
  6234. return
  6235. proc.done()
  6236. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6237. else:
  6238. make_negative_film()
  6239. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  6240. """
  6241. Exports a Geometry Object to an SVG file in positive black.
  6242. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6243. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  6244. :param filename: Path to the SVG file to save to.
  6245. :param scale_factor: factor by which to change/scale the thickness of the features
  6246. :param use_thread: if to be run in a separate thread; boolean
  6247. :return:
  6248. """
  6249. self.report_usage("export_svg_black()")
  6250. if filename is None:
  6251. filename = self.defaults["global_last_save_folder"]
  6252. self.log.debug("export_svg() black")
  6253. try:
  6254. obj = self.collection.get_by_name(str(obj_name))
  6255. except:
  6256. # TODO: The return behavior has not been established... should raise exception?
  6257. return "Could not retrieve object: %s" % obj_name
  6258. try:
  6259. box = self.collection.get_by_name(str(box_name))
  6260. except:
  6261. # TODO: The return behavior has not been established... should raise exception?
  6262. return "Could not retrieve object: %s" % box_name
  6263. if box is None:
  6264. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  6265. box = obj
  6266. def make_black_film():
  6267. exported_svg = obj.export_svg(scale_factor=scale_factor)
  6268. self.progress.emit(40)
  6269. # Change the attributes of the exported SVG
  6270. # We don't need stroke-width
  6271. # We set opacity to maximum
  6272. # We set the colour to WHITE
  6273. root = ET.fromstring(exported_svg)
  6274. for child in root:
  6275. child.set('fill', '#000000')
  6276. child.set('opacity', '1.0')
  6277. child.set('stroke', '#000000')
  6278. exported_svg = ET.tostring(root)
  6279. # Determine bounding area for svg export
  6280. bounds = box.bounds()
  6281. size = box.size()
  6282. # This contain the measure units
  6283. uom = obj.units.lower()
  6284. # Define a boundary around SVG of about 1.0mm (~39mils)
  6285. if uom in "mm":
  6286. boundary = 1.0
  6287. else:
  6288. boundary = 0.0393701
  6289. self.progress.emit(80)
  6290. # Convert everything to strings for use in the xml doc
  6291. svgwidth = str(size[0] + (2 * boundary))
  6292. svgheight = str(size[1] + (2 * boundary))
  6293. minx = str(bounds[0] - boundary)
  6294. miny = str(bounds[1] + boundary + size[1])
  6295. self.log.debug(minx)
  6296. self.log.debug(miny)
  6297. # Add a SVG Header and footer to the svg output from shapely
  6298. # The transform flips the Y Axis so that everything renders
  6299. # properly within svg apps such as inkscape
  6300. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6301. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6302. svg_header += 'width="' + svgwidth + uom + '" '
  6303. svg_header += 'height="' + svgheight + uom + '" '
  6304. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6305. svg_header += '>'
  6306. svg_header += '<g transform="scale(1,-1)">'
  6307. svg_footer = '</g> </svg>'
  6308. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  6309. self.progress.emit(90)
  6310. # Parse the xml through a xml parser just to add line feeds
  6311. # and to make it look more pretty for the output
  6312. doc = parse_xml_string(svg_elem)
  6313. try:
  6314. with open(filename, 'w') as fp:
  6315. fp.write(doc.toprettyxml())
  6316. except PermissionError:
  6317. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6318. "Most likely another app is holding the file open and not accessible."))
  6319. return 'fail'
  6320. self.progress.emit(100)
  6321. if self.defaults["global_open_style"] is False:
  6322. self.file_opened.emit("SVG", filename)
  6323. self.file_saved.emit("SVG", filename)
  6324. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  6325. if use_thread is True:
  6326. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  6327. def job_thread_film(app_obj):
  6328. try:
  6329. make_black_film()
  6330. except Exception as e:
  6331. proc.done()
  6332. return
  6333. proc.done()
  6334. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  6335. else:
  6336. make_black_film()
  6337. def save_source_file(self, obj_name, filename, use_thread=True):
  6338. """
  6339. Exports a FlatCAM Object to an Gerber/Excellon file.
  6340. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6341. :param filename: Path to the Gerber file to save to.
  6342. :param use_thread: if to be run in a separate thread
  6343. :return:
  6344. """
  6345. self.report_usage("save source file()")
  6346. if filename is None:
  6347. filename = self.defaults["global_last_save_folder"]
  6348. self.log.debug("save source file()")
  6349. obj = self.collection.get_by_name(obj_name)
  6350. file_string = StringIO(obj.source_file)
  6351. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6352. try:
  6353. with open(filename, 'w') as file:
  6354. file.writelines('G04*\n')
  6355. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6356. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6357. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6358. file.writelines('G04 Created on : %s*\n' % time_string)
  6359. for line in file_string:
  6360. file.writelines(line)
  6361. except PermissionError:
  6362. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6363. "Most likely another app is holding the file open and not accessible."))
  6364. return 'fail'
  6365. def export_excellon(self, obj_name, filename, use_thread=True):
  6366. """
  6367. Exports a Excellon Object to an Excellon file.
  6368. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6369. :param filename: Path to the Excellon file to save to.
  6370. :param use_thread: if to be run in a separate thread
  6371. :return:
  6372. """
  6373. self.report_usage("export_excellon()")
  6374. if filename is None:
  6375. filename = self.defaults["global_last_save_folder"]
  6376. self.log.debug("export_excellon()")
  6377. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6378. self.defaults["excellon_exp_decimals"]
  6379. )
  6380. units = ''
  6381. try:
  6382. obj = self.collection.get_by_name(str(obj_name))
  6383. except:
  6384. # TODO: The return behavior has not been established... should raise exception?
  6385. return "Could not retrieve object: %s" % obj_name
  6386. # updated units
  6387. eunits = self.defaults["excellon_exp_units"]
  6388. ewhole = self.defaults["excellon_exp_integer"]
  6389. efract = self.defaults["excellon_exp_decimals"]
  6390. ezeros = self.defaults["excellon_exp_zeros"]
  6391. eformat = self.defaults["excellon_exp_format"]
  6392. slot_type = self.defaults["excellon_exp_slot_type"]
  6393. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6394. if fc_units == 'MM':
  6395. factor = 1 if eunits == 'METRIC' else 0.03937
  6396. else:
  6397. factor = 25.4 if eunits == 'METRIC' else 1
  6398. def make_excellon():
  6399. try:
  6400. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6401. header = 'M48\n'
  6402. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6403. (str(self.version), str(self.version_date))
  6404. header += ';Filename: %s' % str(obj_name) + '\n'
  6405. header += ';Created on : %s' % time_str + '\n'
  6406. if eformat == 'dec':
  6407. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6408. header += eunits + '\n'
  6409. for tool in obj.tools:
  6410. if eunits == 'METRIC':
  6411. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6412. tool=str(tool),
  6413. dec=2)
  6414. else:
  6415. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6416. tool=str(tool),
  6417. dec=4)
  6418. else:
  6419. if ezeros == 'LZ':
  6420. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6421. form='ndec', e_zeros='LZ', factor=factor,
  6422. slot_type=slot_type)
  6423. header += '%s,%s\n' % (eunits, 'LZ')
  6424. header += format_exc
  6425. for tool in obj.tools:
  6426. if eunits == 'METRIC':
  6427. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6428. tool=str(tool),
  6429. dec=2)
  6430. else:
  6431. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6432. tool=str(tool),
  6433. dec=4)
  6434. else:
  6435. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6436. form='ndec', e_zeros='TZ', factor=factor,
  6437. slot_type=slot_type)
  6438. header += '%s,%s\n' % (eunits, 'TZ')
  6439. header += format_exc
  6440. for tool in obj.tools:
  6441. if eunits == 'METRIC':
  6442. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6443. tool=str(tool),
  6444. dec=2)
  6445. else:
  6446. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6447. tool=str(tool),
  6448. dec=4)
  6449. header += '%\n'
  6450. footer = 'M30\n'
  6451. exported_excellon = header
  6452. exported_excellon += excellon_code
  6453. exported_excellon += footer
  6454. try:
  6455. with open(filename, 'w') as fp:
  6456. fp.write(exported_excellon)
  6457. except PermissionError:
  6458. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6459. "Most likely another app is holding the file open and not accessible."))
  6460. return 'fail'
  6461. if self.defaults["global_open_style"] is False:
  6462. self.file_opened.emit("Excellon", filename)
  6463. self.file_saved.emit("Excellon", filename)
  6464. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  6465. except Exception as e:
  6466. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6467. return 'fail'
  6468. if use_thread is True:
  6469. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6470. def job_thread_exc(app_obj):
  6471. ret = make_excellon()
  6472. if ret == 'fail':
  6473. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  6474. return
  6475. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6476. else:
  6477. ret = make_excellon()
  6478. if ret == 'fail':
  6479. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  6480. return
  6481. def export_gerber(self, obj_name, filename, use_thread=True):
  6482. """
  6483. Exports a Gerber Object to an Gerber file.
  6484. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6485. :param filename: Path to the Gerber file to save to.
  6486. :param use_thread: if to be run in a separate thread
  6487. :return:
  6488. """
  6489. self.report_usage("export_gerber()")
  6490. if filename is None:
  6491. filename = self.defaults["global_last_save_folder"]
  6492. self.log.debug("export_gerber()")
  6493. try:
  6494. obj = self.collection.get_by_name(str(obj_name))
  6495. except:
  6496. # TODO: The return behavior has not been established... should raise exception?
  6497. return "Could not retrieve object: %s" % obj_name
  6498. # updated units
  6499. gunits = self.defaults["gerber_exp_units"]
  6500. gwhole = self.defaults["gerber_exp_integer"]
  6501. gfract = self.defaults["gerber_exp_decimals"]
  6502. gzeros = self.defaults["gerber_exp_zeros"]
  6503. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6504. if fc_units == 'MM':
  6505. factor = 1 if gunits == 'MM' else 0.03937
  6506. else:
  6507. factor = 25.4 if gunits == 'MM' else 1
  6508. def make_gerber():
  6509. try:
  6510. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6511. header = 'G04*\n'
  6512. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6513. (str(self.version), str(self.version_date))
  6514. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6515. header += 'G04 Created on : %s*' % time_str + '\n'
  6516. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6517. header += "%MO{units}*%\n".format(units=gunits)
  6518. for apid in obj.apertures:
  6519. if obj.apertures[apid]['type'] == 'C':
  6520. header += "%ADD{apid}{type},{size}*%\n".format(
  6521. apid=str(apid),
  6522. type='C',
  6523. size=(factor * obj.apertures[apid]['size'])
  6524. )
  6525. elif obj.apertures[apid]['type'] == 'R':
  6526. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6527. apid=str(apid),
  6528. type='R',
  6529. width=(factor * obj.apertures[apid]['width']),
  6530. height=(factor * obj.apertures[apid]['height'])
  6531. )
  6532. elif obj.apertures[apid]['type'] == 'O':
  6533. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6534. apid=str(apid),
  6535. type='O',
  6536. width=(factor * obj.apertures[apid]['width']),
  6537. height=(factor * obj.apertures[apid]['height'])
  6538. )
  6539. header += '\n'
  6540. # obsolete units but some software may need it
  6541. if gunits == 'IN':
  6542. header += 'G70*\n'
  6543. else:
  6544. header += 'G71*\n'
  6545. # Absolute Mode
  6546. header += 'G90*\n'
  6547. header += 'G01*\n'
  6548. # positive polarity
  6549. header += '%LPD*%\n'
  6550. footer = 'M02*\n'
  6551. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6552. exported_gerber = header
  6553. exported_gerber += gerber_code
  6554. exported_gerber += footer
  6555. try:
  6556. with open(filename, 'w') as fp:
  6557. fp.write(exported_gerber)
  6558. except PermissionError:
  6559. self.inform.emit(_("[WARNING] Permission denied, saving not possible.\n"
  6560. "Most likely another app is holding the file open and not accessible."))
  6561. return 'fail'
  6562. if self.defaults["global_open_style"] is False:
  6563. self.file_opened.emit("Gerber", filename)
  6564. self.file_saved.emit("Gerber", filename)
  6565. self.inform.emit(_("[success] Gerber file exported to %s") % filename)
  6566. except Exception as e:
  6567. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6568. return 'fail'
  6569. if use_thread is True:
  6570. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6571. def job_thread_exc(app_obj):
  6572. ret = make_gerber()
  6573. if ret == 'fail':
  6574. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  6575. return
  6576. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6577. else:
  6578. ret = make_gerber()
  6579. if ret == 'fail':
  6580. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  6581. return
  6582. def export_dxf(self, obj_name, filename, use_thread=True):
  6583. """
  6584. Exports a Geometry Object to an DXF file.
  6585. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6586. :param filename: Path to the DXF file to save to.
  6587. :param use_thread: if to be run in a separate thread
  6588. :return:
  6589. """
  6590. self.report_usage("export_dxf()")
  6591. if filename is None:
  6592. filename = self.defaults["global_last_save_folder"]
  6593. self.log.debug("export_dxf()")
  6594. format_exc = ''
  6595. units = ''
  6596. try:
  6597. obj = self.collection.get_by_name(str(obj_name))
  6598. except:
  6599. # TODO: The return behavior has not been established... should raise exception?
  6600. return "Could not retrieve object: %s" % obj_name
  6601. # updated units
  6602. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6603. if units == 'IN' or units == 'INCH':
  6604. units = 'INCH'
  6605. elif units == 'MM' or units == 'METIRC':
  6606. units ='METRIC'
  6607. def make_dxf():
  6608. try:
  6609. dxf_code = obj.export_dxf()
  6610. dxf_code.saveas(filename)
  6611. if self.defaults["global_open_style"] is False:
  6612. self.file_opened.emit("DXF", filename)
  6613. self.file_saved.emit("DXF", filename)
  6614. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  6615. except:
  6616. return 'fail'
  6617. if use_thread is True:
  6618. with self.proc_container.new(_("Exporting DXF")) as proc:
  6619. def job_thread_exc(app_obj):
  6620. ret = make_dxf()
  6621. if ret == 'fail':
  6622. app_obj.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6623. return
  6624. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6625. else:
  6626. ret = make_dxf()
  6627. if ret == 'fail':
  6628. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6629. return
  6630. def import_svg(self, filename, geo_type='geometry', outname=None):
  6631. """
  6632. Adds a new Geometry Object to the projects and populates
  6633. it with shapes extracted from the SVG file.
  6634. :param filename: Path to the SVG file.
  6635. :param outname:
  6636. :return:
  6637. """
  6638. self.report_usage("import_svg()")
  6639. obj_type = ""
  6640. if geo_type is None or geo_type == "geometry":
  6641. obj_type = "geometry"
  6642. elif geo_type == "gerber":
  6643. obj_type = geo_type
  6644. else:
  6645. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6646. "Only Geometry and Gerber are supported"))
  6647. return
  6648. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6649. def obj_init(geo_obj, app_obj):
  6650. geo_obj.import_svg(filename, obj_type, units=units)
  6651. geo_obj.multigeo = False
  6652. with self.proc_container.new(_("Importing SVG")) as proc:
  6653. # Object name
  6654. name = outname or filename.split('/')[-1].split('\\')[-1]
  6655. self.new_object(obj_type, name, obj_init, autoselected=False)
  6656. self.progress.emit(20)
  6657. # Register recent file
  6658. self.file_opened.emit("svg", filename)
  6659. # GUI feedback
  6660. self.inform.emit(_("[success] Opened: %s") % filename)
  6661. self.progress.emit(100)
  6662. def import_dxf(self, filename, geo_type='geometry', outname=None):
  6663. """
  6664. Adds a new Geometry Object to the projects and populates
  6665. it with shapes extracted from the DXF file.
  6666. :param filename: Path to the DXF file.
  6667. :param outname:
  6668. :type putname: str
  6669. :return:
  6670. """
  6671. self.report_usage("import_dxf()")
  6672. obj_type = ""
  6673. if geo_type is None or geo_type == "geometry":
  6674. obj_type = "geometry"
  6675. elif geo_type == "gerber":
  6676. obj_type = geo_type
  6677. else:
  6678. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6679. "Only Geometry and Gerber are supported"))
  6680. return
  6681. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6682. def obj_init(geo_obj, app_obj):
  6683. geo_obj.import_dxf(filename, obj_type, units=units)
  6684. geo_obj.multigeo = False
  6685. with self.proc_container.new(_("Importing DXF")) as proc:
  6686. # Object name
  6687. name = outname or filename.split('/')[-1].split('\\')[-1]
  6688. self.new_object(obj_type, name, obj_init, autoselected=False)
  6689. self.progress.emit(20)
  6690. # Register recent file
  6691. self.file_opened.emit("dxf", filename)
  6692. # GUI feedback
  6693. self.inform.emit(_("[success] Opened: %s") % filename)
  6694. self.progress.emit(100)
  6695. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  6696. """
  6697. Adds a new Geometry Object to the projects and populates
  6698. it with shapes extracted from the SVG file.
  6699. :param filename: Path to the SVG file.
  6700. :param o_type: type of FlatCAM objeect
  6701. :param dpi: dot per inch
  6702. :param mode: black or color
  6703. :param mask: dictate the level of detail
  6704. :param outname: name for the resulting file
  6705. :return:
  6706. """
  6707. self.report_usage("import_image()")
  6708. if o_type is None or o_type == "geometry":
  6709. obj_type = "geometry"
  6710. elif o_type == "gerber":
  6711. obj_type = o_type
  6712. else:
  6713. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6714. "Only Geometry and Gerber are supported"))
  6715. return
  6716. def obj_init(geo_obj, app_obj):
  6717. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  6718. geo_obj.multigeo = False
  6719. with self.proc_container.new(_("Importing Image")) as proc:
  6720. # Object name
  6721. name = outname or filename.split('/')[-1].split('\\')[-1]
  6722. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  6723. self.new_object(obj_type, name, obj_init)
  6724. self.progress.emit(20)
  6725. # Register recent file
  6726. self.file_opened.emit("image", filename)
  6727. # GUI feedback
  6728. self.inform.emit(_("[success] Opened: %s") % filename)
  6729. self.progress.emit(100)
  6730. def open_gerber(self, filename, outname=None):
  6731. """
  6732. Opens a Gerber file, parses it and creates a new object for
  6733. it in the program. Thread-safe.
  6734. :param outname: Name of the resulting object. None causes the
  6735. name to be that of the file.
  6736. :param filename: Gerber file filename
  6737. :type filename: str
  6738. :param follow: If true, the parser will not create polygons, just lines
  6739. following the gerber path.
  6740. :type follow: bool
  6741. :return: None
  6742. """
  6743. # How the object should be initialized
  6744. def obj_init(gerber_obj, app_obj):
  6745. assert isinstance(gerber_obj, FlatCAMGerber), \
  6746. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  6747. # Opening the file happens here
  6748. self.progress.emit(30)
  6749. try:
  6750. gerber_obj.parse_file(filename)
  6751. except IOError:
  6752. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  6753. app_obj.progress.emit(0)
  6754. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  6755. return "fail"
  6756. except ParseError as err:
  6757. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename,
  6758. error=str(err)))
  6759. app_obj.progress.emit(0)
  6760. self.log.error(str(err))
  6761. return "fail"
  6762. except Exception as e:
  6763. log.debug("App.open_gerber() --> %s" % str(e))
  6764. msg = _("[ERROR] An internal error has occurred. See shell.\n")
  6765. msg += traceback.format_exc()
  6766. app_obj.inform.emit(msg)
  6767. return "fail"
  6768. if gerber_obj.is_empty():
  6769. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  6770. # self.collection.set_active(gerber_obj.options["name"])
  6771. # self.collection.delete_active()
  6772. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  6773. return "fail"
  6774. # Further parsing
  6775. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  6776. App.log.debug("open_gerber()")
  6777. with self.proc_container.new(_("Opening Gerber")) as proc:
  6778. self.progress.emit(10)
  6779. # Object name
  6780. name = outname or filename.split('/')[-1].split('\\')[-1]
  6781. # # ## Object creation # ##
  6782. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  6783. if ret == 'fail':
  6784. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  6785. return
  6786. # Register recent file
  6787. self.file_opened.emit("gerber", filename)
  6788. self.progress.emit(100)
  6789. # GUI feedback
  6790. self.inform.emit(_("[success] Opened: %s") % filename)
  6791. def open_excellon(self, filename, outname=None):
  6792. """
  6793. Opens an Excellon file, parses it and creates a new object for
  6794. it in the program. Thread-safe.
  6795. :param outname: Name of the resulting object. None causes the
  6796. name to be that of the file.
  6797. :param filename: Excellon file filename
  6798. :type filename: str
  6799. :return: None
  6800. """
  6801. App.log.debug("open_excellon()")
  6802. # How the object should be initialized
  6803. def obj_init(excellon_obj, app_obj):
  6804. # self.progress.emit(20)
  6805. try:
  6806. ret = excellon_obj.parse_file(filename=filename)
  6807. if ret == "fail":
  6808. log.debug("Excellon parsing failed.")
  6809. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  6810. return "fail"
  6811. except IOError:
  6812. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  6813. log.debug("Could not open Excellon object.")
  6814. self.progress.emit(0) # TODO: self and app_bjj mixed
  6815. return "fail"
  6816. except:
  6817. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  6818. msg += traceback.format_exc()
  6819. app_obj.inform.emit(msg)
  6820. return "fail"
  6821. ret = excellon_obj.create_geometry()
  6822. if ret == 'fail':
  6823. log.debug("Could not create geometry for Excellon object.")
  6824. return "fail"
  6825. for tool in excellon_obj.tools:
  6826. if excellon_obj.tools[tool]['solid_geometry']:
  6827. return
  6828. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  6829. return "fail"
  6830. with self.proc_container.new(_("Opening Excellon.")):
  6831. # Object name
  6832. name = outname or filename.split('/')[-1].split('\\')[-1]
  6833. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  6834. if ret_val == 'fail':
  6835. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  6836. return
  6837. # Register recent file
  6838. self.file_opened.emit("excellon", filename)
  6839. # GUI feedback
  6840. self.inform.emit(_("[success] Opened: %s") % filename)
  6841. def open_gcode(self, filename, outname=None):
  6842. """
  6843. Opens a G-gcode file, parses it and creates a new object for
  6844. it in the program. Thread-safe.
  6845. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6846. :param filename: G-code file filename
  6847. :type filename: str
  6848. :return: None
  6849. """
  6850. App.log.debug("open_gcode()")
  6851. # How the object should be initialized
  6852. def obj_init(job_obj, app_obj_):
  6853. """
  6854. :param job_obj: the resulting object
  6855. :type app_obj_: App
  6856. """
  6857. assert isinstance(app_obj_, App), \
  6858. "Initializer expected App, got %s" % type(app_obj_)
  6859. self.progress.emit(10)
  6860. try:
  6861. f = open(filename)
  6862. gcode = f.read()
  6863. f.close()
  6864. except IOError:
  6865. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  6866. self.progress.emit(0)
  6867. return "fail"
  6868. job_obj.gcode = gcode
  6869. self.progress.emit(20)
  6870. ret = job_obj.gcode_parse()
  6871. if ret == "fail":
  6872. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  6873. return "fail"
  6874. self.progress.emit(60)
  6875. job_obj.create_geometry()
  6876. with self.proc_container.new(_("Opening G-Code.")):
  6877. # Object name
  6878. name = outname or filename.split('/')[-1].split('\\')[-1]
  6879. # New object creation and file processing
  6880. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  6881. if ret == 'fail':
  6882. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  6883. "Attempting to create a FlatCAM CNCJob Object from "
  6884. "G-Code file failed during processing"))
  6885. return "fail"
  6886. # Register recent file
  6887. self.file_opened.emit("cncjob", filename)
  6888. # GUI feedback
  6889. self.inform.emit(_("[success] Opened: %s") % filename)
  6890. self.progress.emit(100)
  6891. def open_config_file(self, filename, run_from_arg=None):
  6892. """
  6893. Loads a config file from the specified file.
  6894. :param filename: Name of the file from which to load.
  6895. :type filename: str
  6896. :return: None
  6897. """
  6898. App.log.debug("Opening config file: " + filename)
  6899. # add the tab if it was closed
  6900. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  6901. # first clear previous text in text editor (if any)
  6902. self.ui.code_editor.clear()
  6903. # Switch plot_area to CNCJob tab
  6904. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6905. try:
  6906. if filename:
  6907. f = QtCore.QFile(filename)
  6908. if f.open(QtCore.QIODevice.ReadOnly):
  6909. stream = QtCore.QTextStream(f)
  6910. gcode_edited = stream.readAll()
  6911. self.ui.code_editor.setPlainText(gcode_edited)
  6912. f.close()
  6913. except IOError:
  6914. App.log.error("Failed to open config file: %s" % filename)
  6915. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  6916. return
  6917. def open_project(self, filename, run_from_arg=None):
  6918. """
  6919. Loads a project from the specified file.
  6920. 1) Loads and parses file
  6921. 2) Registers the file as recently opened.
  6922. 3) Calls on_file_new()
  6923. 4) Updates options
  6924. 5) Calls new_object() with the object's from_dict() as init method.
  6925. 6) Calls plot_all()
  6926. :param filename: Name of the file from which to load.
  6927. :type filename: str
  6928. :param run_from_arg: True if run for arguments
  6929. :return: None
  6930. """
  6931. App.log.debug("Opening project: " + filename)
  6932. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  6933. # Open and parse an uncompressed Project file
  6934. try:
  6935. f = open(filename, 'r')
  6936. except IOError:
  6937. App.log.error("Failed to open project file: %s" % filename)
  6938. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6939. return
  6940. try:
  6941. d = json.load(f, object_hook=dict2obj)
  6942. except Exception as e:
  6943. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  6944. (filename, str(e)))
  6945. f.close()
  6946. # Open and parse a compressed Project file
  6947. try:
  6948. with lzma.open(filename) as f:
  6949. file_content = f.read().decode('utf-8')
  6950. d = json.loads(file_content, object_hook=dict2obj)
  6951. except Exception as e:
  6952. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  6953. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6954. return
  6955. # Clear the current project
  6956. # # NOT THREAD SAFE # ##
  6957. if run_from_arg is True:
  6958. pass
  6959. else:
  6960. self.on_file_new()
  6961. # Project options
  6962. self.options.update(d['options'])
  6963. self.project_filename = filename
  6964. self.set_screen_units(self.options["units"])
  6965. # Re create objects
  6966. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  6967. for obj in d['objs']:
  6968. def obj_init(obj_inst, app_inst):
  6969. obj_inst.from_dict(obj)
  6970. App.log.debug("Recreating from opened project an %s object: %s" %
  6971. (obj['kind'].capitalize(), obj['options']['name']))
  6972. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"), obj['kind'].upper(), obj['options']['name']))
  6973. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  6974. # self.plot_all()
  6975. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  6976. self.should_we_save = False
  6977. self.file_opened.emit("project", filename)
  6978. self.set_ui_title(name=self.project_filename)
  6979. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  6980. def propagate_defaults(self, silent=False):
  6981. """
  6982. This method is used to set default values in classes. It's
  6983. an alternative to project options but allows the use
  6984. of values invisible to the user.
  6985. :return: None
  6986. """
  6987. if silent is False:
  6988. self.log.debug("propagate_defaults()")
  6989. # Which objects to update the given parameters.
  6990. routes = {
  6991. "global_zdownrate": CNCjob,
  6992. "excellon_zeros": Excellon,
  6993. "excellon_format_upper_in": Excellon,
  6994. "excellon_format_lower_in": Excellon,
  6995. "excellon_format_upper_mm": Excellon,
  6996. "excellon_format_lower_mm": Excellon,
  6997. "excellon_units": Excellon,
  6998. "gerber_use_buffer_for_union": Gerber,
  6999. "geometry_multidepth": Geometry
  7000. }
  7001. for param in routes:
  7002. if param in routes[param].defaults:
  7003. try:
  7004. routes[param].defaults[param] = self.defaults[param]
  7005. if silent is False:
  7006. self.log.debug(" " + param + " OK")
  7007. except KeyError:
  7008. if silent is False:
  7009. self.log.debug(" ERROR: " + param + " not in defaults.")
  7010. else:
  7011. # Try extracting the name:
  7012. # classname_param here is param in the object
  7013. if param.find(routes[param].__name__.lower() + "_") == 0:
  7014. p = param[len(routes[param].__name__) + 1:]
  7015. if p in routes[param].defaults:
  7016. routes[param].defaults[p] = self.defaults[param]
  7017. if silent is False:
  7018. self.log.debug(" " + param + " OK!")
  7019. def restore_main_win_geom(self):
  7020. try:
  7021. self.ui.setGeometry(self.defaults["global_def_win_x"],
  7022. self.defaults["global_def_win_y"],
  7023. self.defaults["global_def_win_w"],
  7024. self.defaults["global_def_win_h"])
  7025. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  7026. settings = QSettings("Open Source", "FlatCAM")
  7027. if settings.contains("maximized_gui"):
  7028. maximized_ui = settings.value('maximized_gui', type=bool)
  7029. if maximized_ui is True:
  7030. self.ui.showMaximized()
  7031. except KeyError as e:
  7032. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  7033. def plot_all(self, zoom=True):
  7034. """
  7035. Re-generates all plots from all objects.
  7036. :return: None
  7037. """
  7038. self.log.debug("Plot_all()")
  7039. for obj in self.collection.get_list():
  7040. def worker_task(obj):
  7041. with self.proc_container.new("Plotting"):
  7042. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7043. if zoom:
  7044. self.object_plotted.emit(obj)
  7045. # Send to worker
  7046. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  7047. def register_folder(self, filename):
  7048. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7049. def register_save_folder(self, filename):
  7050. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7051. def set_progress_bar(self, percentage, text=""):
  7052. self.ui.progress_bar.setValue(int(percentage))
  7053. def setup_shell(self):
  7054. """
  7055. Creates shell functions. Runs once at startup.
  7056. :return: None
  7057. """
  7058. self.log.debug("setup_shell()")
  7059. def shelp(p=None):
  7060. if not p:
  7061. return _("Available commands:\n") + \
  7062. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  7063. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  7064. if p not in commands:
  7065. return "Unknown command: %s" % p
  7066. return commands[p]["help"]
  7067. # --- Migrated to new architecture ---
  7068. # def options(name):
  7069. # ops = self.collection.get_by_name(str(name)).options
  7070. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  7071. def h(*args):
  7072. """
  7073. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  7074. and standalone parameters into list.
  7075. """
  7076. kwa = {}
  7077. a = []
  7078. n = len(args)
  7079. name = None
  7080. for i in range(n):
  7081. match = re.search(r'^-([a-zA-Z].*)', args[i])
  7082. if match:
  7083. assert name is None
  7084. name = match.group(1)
  7085. continue
  7086. if name is None:
  7087. a.append(args[i])
  7088. else:
  7089. kwa[name] = args[i]
  7090. name = None
  7091. return a, kwa
  7092. @contextmanager
  7093. def wait_signal(signal, timeout=10000):
  7094. """
  7095. Block loop until signal emitted, timeout (ms) elapses
  7096. or unhandled exception happens in a thread.
  7097. :param timeout: time after which the loop is exited
  7098. :param signal: Signal to wait for.
  7099. """
  7100. loop = QtCore.QEventLoop()
  7101. # Normal termination
  7102. signal.connect(loop.quit)
  7103. # Termination by exception in thread
  7104. self.thread_exception.connect(loop.quit)
  7105. status = {'timed_out': False}
  7106. def report_quit():
  7107. status['timed_out'] = True
  7108. loop.quit()
  7109. yield
  7110. # Temporarily change how exceptions are managed.
  7111. oeh = sys.excepthook
  7112. ex = []
  7113. def except_hook(type_, value, traceback_):
  7114. ex.append(value)
  7115. oeh(type_, value, traceback_)
  7116. sys.excepthook = except_hook
  7117. # Terminate on timeout
  7118. if timeout is not None:
  7119. QtCore.QTimer.singleShot(timeout, report_quit)
  7120. # # ## Block ## ##
  7121. loop.exec_()
  7122. # Restore exception management
  7123. sys.excepthook = oeh
  7124. if ex:
  7125. self.raiseTclError(str(ex[0]))
  7126. if status['timed_out']:
  7127. raise Exception('Timed out!')
  7128. def make_docs():
  7129. output = ''
  7130. import collections
  7131. od = collections.OrderedDict(sorted(commands.items()))
  7132. for cmd_, val in od.items():
  7133. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  7134. t = val['help']
  7135. usage_i = t.find('>')
  7136. if usage_i < 0:
  7137. expl = t
  7138. output += expl + '\n\n'
  7139. continue
  7140. expl = t[:usage_i - 1]
  7141. output += expl + '\n\n'
  7142. end_usage_i = t[usage_i:].find('\n')
  7143. if end_usage_i < 0:
  7144. end_usage_i = len(t[usage_i:])
  7145. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  7146. else:
  7147. extras = t[usage_i+end_usage_i+1:]
  7148. parts = [s.strip() for s in extras.split('\n')]
  7149. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  7150. for p in parts:
  7151. output += ' ' + p + '\n\n'
  7152. return output
  7153. '''
  7154. Howto implement TCL shell commands:
  7155. All parameters passed to command should be possible to set as None and test it afterwards.
  7156. This is because we need to see error caused in tcl,
  7157. if None value as default parameter is not allowed TCL will return empty error.
  7158. Use:
  7159. def mycommand(name=None,...):
  7160. Test it like this:
  7161. if name is None:
  7162. self.raise_tcl_error('Argument name is missing.')
  7163. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  7164. otherwise we will miss it and processing will silently continue.
  7165. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  7166. which is catched in exec_command and displayed in TCL shell console with red background.
  7167. Error in console is displayed with TCL trace.
  7168. This behavior works only within main thread,
  7169. errors with promissed tasks can be catched and detected only with log.
  7170. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  7171. TCL shell.
  7172. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  7173. '''
  7174. commands = {
  7175. 'help': {
  7176. 'fcn': shelp,
  7177. 'help': _("Shows list of commands.")
  7178. },
  7179. }
  7180. # Import/overwrite tcl commands as objects of TclCommand descendants
  7181. # This modifies the variable 'commands'.
  7182. tclCommands.register_all_commands(self, commands)
  7183. # Add commands to the tcl interpreter
  7184. for cmd in commands:
  7185. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  7186. # Make the tcl puts function return instead of print to stdout
  7187. self.tcl.eval('''
  7188. rename puts original_puts
  7189. proc puts {args} {
  7190. if {[llength $args] == 1} {
  7191. return "[lindex $args 0]"
  7192. } else {
  7193. eval original_puts $args
  7194. }
  7195. }
  7196. ''')
  7197. def setup_recent_items(self):
  7198. # TODO: Move this to constructor
  7199. icons = {
  7200. "gerber": "share/flatcam_icon16.png",
  7201. "excellon": "share/drill16.png",
  7202. 'geometry': "share/geometry16.png",
  7203. "cncjob": "share/cnc16.png",
  7204. "project": "share/project16.png",
  7205. "svg": "share/geometry16.png",
  7206. "dxf": "share/dxf16.png",
  7207. "pdf": "share/pdf32.png",
  7208. "image": "share/image16.png"
  7209. }
  7210. openers = {
  7211. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7212. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7213. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7214. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7215. 'project': self.open_project,
  7216. 'svg': self.import_svg,
  7217. 'dxf': self.import_dxf,
  7218. 'image': self.import_image,
  7219. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7220. }
  7221. # Open recent file for files
  7222. try:
  7223. f = open(self.data_path + '/recent.json')
  7224. except IOError:
  7225. App.log.error("Failed to load recent item list.")
  7226. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  7227. return
  7228. try:
  7229. self.recent = json.load(f)
  7230. except json.scanner.JSONDecodeError:
  7231. App.log.error("Failed to parse recent item list.")
  7232. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  7233. f.close()
  7234. return
  7235. f.close()
  7236. # Open recent file for projects
  7237. try:
  7238. fp = open(self.data_path + '/recent_projects.json')
  7239. except IOError:
  7240. App.log.error("Failed to load recent project item list.")
  7241. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent projects item list."))
  7242. return
  7243. try:
  7244. self.recent_projects = json.load(fp)
  7245. except json.scanner.JSONDecodeError:
  7246. App.log.error("Failed to parse recent project item list.")
  7247. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent project item list."))
  7248. fp.close()
  7249. return
  7250. fp.close()
  7251. # Closure needed to create callbacks in a loop.
  7252. # Otherwise late binding occurs.
  7253. def make_callback(func, fname):
  7254. def opener():
  7255. func(fname)
  7256. return opener
  7257. def reset_recent_files():
  7258. # Reset menu
  7259. self.ui.recent.clear()
  7260. self.recent = []
  7261. try:
  7262. f = open(self.data_path + '/recent.json', 'w')
  7263. except IOError:
  7264. App.log.error("Failed to open recent items file for writing.")
  7265. return
  7266. json.dump(self.recent, f)
  7267. def reset_recent_projects():
  7268. # Reset menu
  7269. self.ui.recent_projects.clear()
  7270. self.recent_projects = []
  7271. try:
  7272. fp = open(self.data_path + '/recent_projects.json', 'w')
  7273. except IOError:
  7274. App.log.error("Failed to open recent projects items file for writing.")
  7275. return
  7276. json.dump(self.recent, fp)
  7277. # Reset menu
  7278. self.ui.recent.clear()
  7279. self.ui.recent_projects.clear()
  7280. # Create menu items for projects
  7281. for recent in self.recent_projects:
  7282. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7283. if recent['kind'] == 'project':
  7284. try:
  7285. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7286. # Attach callback
  7287. o = make_callback(openers[recent["kind"]], recent['filename'])
  7288. action.triggered.connect(o)
  7289. self.ui.recent_projects.addAction(action)
  7290. except KeyError:
  7291. App.log.error("Unsupported file type: %s" % recent["kind"])
  7292. # Last action in Recent Files menu is one that Clear the content
  7293. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  7294. clear_action_proj.triggered.connect(reset_recent_projects)
  7295. self.ui.recent_projects.addSeparator()
  7296. self.ui.recent_projects.addAction(clear_action_proj)
  7297. # Create menu items for files
  7298. for recent in self.recent:
  7299. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7300. if recent['kind'] != 'project':
  7301. try:
  7302. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7303. # Attach callback
  7304. o = make_callback(openers[recent["kind"]], recent['filename'])
  7305. action.triggered.connect(o)
  7306. self.ui.recent.addAction(action)
  7307. except KeyError:
  7308. App.log.error("Unsupported file type: %s" % recent["kind"])
  7309. # Last action in Recent Files menu is one that Clear the content
  7310. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  7311. clear_action.triggered.connect(reset_recent_files)
  7312. self.ui.recent.addSeparator()
  7313. self.ui.recent.addAction(clear_action)
  7314. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7315. # self.ui.menufilerecent.set_submenu(recent_menu)
  7316. # recent_menu.show_all()
  7317. # self.ui.recent.show()
  7318. self.log.debug("Recent items list has been populated.")
  7319. def setup_component_editor(self):
  7320. # label = QtWidgets.QLabel("Choose an item from Project")
  7321. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7322. sel_title = QtWidgets.QTextEdit(
  7323. _('<b>Shortcut Key List</b>'))
  7324. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7325. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7326. settings = QSettings("Open Source", "FlatCAM")
  7327. if settings.contains("notebook_font_size"):
  7328. fsize = settings.value('notebook_font_size', type=int)
  7329. else:
  7330. fsize = 12
  7331. tsize = fsize + int(fsize / 2)
  7332. selected_text = _('''
  7333. <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  7334. <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7335. The normal flow when working in FlatCAM is the following:</span></p>
  7336. <ol>
  7337. <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  7338. <br />
  7339. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  7340. &nbsp;</li>
  7341. <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7342. <br />
  7343. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  7344. <br />
  7345. You can change the parameters in this screen and the flow direction is like this:<br />
  7346. <br />
  7347. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7348. </ol>
  7349. <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  7350. '''.format(fsize=fsize, tsize=tsize))
  7351. sel_title.setText(selected_text)
  7352. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7353. self.ui.selected_scroll_area.setWidget(sel_title)
  7354. def setup_obj_classes(self):
  7355. """
  7356. Sets up application specifics on the FlatCAMObj class.
  7357. :return: None
  7358. """
  7359. FlatCAMObj.app = self
  7360. ObjectCollection.app = self
  7361. Gerber.app = self
  7362. Excellon.app = self
  7363. Geometry.app = self
  7364. CNCjob.app = self
  7365. FCProcess.app = self
  7366. FCProcessContainer.app = self
  7367. def version_check(self):
  7368. """
  7369. Checks for the latest version of the program. Alerts the
  7370. user if theirs is outdated. This method is meant to be run
  7371. in a separate thread.
  7372. :return: None
  7373. """
  7374. self.log.debug("version_check()")
  7375. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7376. full_url = App.version_url + \
  7377. "?s=" + str(self.defaults['global_serial']) + \
  7378. "&v=" + str(self.version) + \
  7379. "&os=" + str(self.os) + \
  7380. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  7381. else:
  7382. # no_stats dict; just so it won't break things on website
  7383. no_ststs_dict = {}
  7384. no_ststs_dict["global_ststs"] = {}
  7385. full_url = App.version_url + \
  7386. "?s=" + str(self.defaults['global_serial']) + \
  7387. "&v=" + str(self.version) + \
  7388. "&os=" + str(self.os) + \
  7389. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7390. App.log.debug("Checking for updates @ %s" % full_url)
  7391. # ## Get the data
  7392. try:
  7393. f = urllib.request.urlopen(full_url)
  7394. except:
  7395. # App.log.warning("Failed checking for latest version. Could not connect.")
  7396. self.log.warning("Failed checking for latest version. Could not connect.")
  7397. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  7398. return
  7399. try:
  7400. data = json.load(f)
  7401. except Exception as e:
  7402. App.log.error("Could not parse information about latest version.")
  7403. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  7404. App.log.debug("json.load(): %s" % str(e))
  7405. f.close()
  7406. return
  7407. f.close()
  7408. # ## Latest version?
  7409. if self.version >= data["version"]:
  7410. App.log.debug("FlatCAM is up to date!")
  7411. self.inform.emit(_("[success] FlatCAM is up to date!"))
  7412. return
  7413. App.log.debug("Newer version available.")
  7414. self.message.emit(
  7415. _("Newer Version Available"),
  7416. _("There is a newer version of FlatCAM available for download:\n\n") +
  7417. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  7418. _("info")
  7419. )
  7420. def on_zoom_fit(self, event):
  7421. """
  7422. Callback for zoom-out request. This can be either from the corresponding
  7423. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7424. with axes limits from the geometry bounds of all objects.
  7425. :param event: Ignored.
  7426. :return: None
  7427. """
  7428. self.plotcanvas.fit_view()
  7429. def disable_all_plots(self):
  7430. self.report_usage("disable_all_plots()")
  7431. self.disable_plots(self.collection.get_list())
  7432. self.inform.emit(_("[success] All plots disabled."))
  7433. def disable_other_plots(self):
  7434. self.report_usage("disable_other_plots()")
  7435. self.disable_plots(self.collection.get_non_selected())
  7436. self.inform.emit(_("[success] All non selected plots disabled."))
  7437. def enable_all_plots(self):
  7438. self.report_usage("enable_all_plots()")
  7439. self.enable_plots(self.collection.get_list())
  7440. self.inform.emit(_("[success] All plots enabled."))
  7441. def on_enable_sel_plots(self):
  7442. log.debug("App.on_enable_sel_plot()")
  7443. object_list = self.collection.get_selected()
  7444. self.enable_plots(objects=object_list)
  7445. self.inform.emit(_("[success] Selected plots enabled..."))
  7446. def on_disable_sel_plots(self):
  7447. log.debug("App.on_disable_sel_plot()")
  7448. # self.inform.emit(_("Disabling plots ..."))
  7449. object_list = self.collection.get_selected()
  7450. self.disable_plots(objects=object_list)
  7451. self.inform.emit(_("[success] Selected plots disabled..."))
  7452. def enable_plots(self, objects):
  7453. """
  7454. Disables plots
  7455. :param objects: list of Objects to be enabled
  7456. :return:
  7457. """
  7458. log.debug("Enabling plots ...")
  7459. self.inform.emit(_("Working ..."))
  7460. for obj in objects:
  7461. if obj.options['plot'] is False:
  7462. obj.options['plot'] = True
  7463. self.plots_updated.emit()
  7464. def disable_plots(self, objects):
  7465. """
  7466. Disables plots
  7467. :param objects: list of Objects to be disabled
  7468. :return:
  7469. """
  7470. # if no objects selected then do nothing
  7471. if not self.collection.get_selected():
  7472. return
  7473. log.debug("Disabling plots ...")
  7474. self.inform.emit(_("Working ..."))
  7475. for obj in objects:
  7476. if obj.options['plot'] is True:
  7477. obj.options['plot'] = False
  7478. self.plots_updated.emit()
  7479. def toggle_plots(self, objects):
  7480. """
  7481. Toggle plots visibility
  7482. :param objects: list of Objects for which to be toggled the visibility
  7483. :return:
  7484. """
  7485. # if no objects selected then do nothing
  7486. if not self.collection.get_selected():
  7487. return
  7488. log.debug("Toggling plots ...")
  7489. self.inform.emit(_("Working ..."))
  7490. for obj in objects:
  7491. if obj.options['plot'] is False:
  7492. obj.options['plot'] = True
  7493. else:
  7494. obj.options['plot'] = False
  7495. self.plots_updated.emit()
  7496. def clear_plots(self):
  7497. objects = self.collection.get_list()
  7498. for obj in objects:
  7499. obj.clear(obj == objects[-1])
  7500. # Clear pool to free memory
  7501. self.clear_pool()
  7502. def generate_cnc_job(self, objects):
  7503. self.report_usage("generate_cnc_job()")
  7504. # for obj in objects:
  7505. # obj.generatecncjob()
  7506. for obj in objects:
  7507. obj.on_generatecnc_button_click()
  7508. def save_project(self, filename, quit_action=False):
  7509. """
  7510. Saves the current project to the specified file.
  7511. :param filename: Name of the file in which to save.
  7512. :type filename: str
  7513. :param quit_action: if the project saving will be followed by an app quit; boolean
  7514. :return: None
  7515. """
  7516. self.log.debug("save_project()")
  7517. self.save_in_progress = True
  7518. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  7519. # Capture the latest changes
  7520. # Current object
  7521. try:
  7522. self.collection.get_active().read_form()
  7523. except:
  7524. self.log.debug("There was no active object")
  7525. pass
  7526. # Project options
  7527. self.options_read_form()
  7528. # Serialize the whole project
  7529. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  7530. "options": self.options,
  7531. "version": self.version}
  7532. if self.defaults["global_save_compressed"] is True:
  7533. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  7534. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  7535. # # Write
  7536. f.write(g)
  7537. self.inform.emit(_("[success] Project saved to: %s") % filename)
  7538. else:
  7539. # Open file
  7540. try:
  7541. f = open(filename, 'w')
  7542. except IOError:
  7543. App.log.error("Failed to open file for saving: %s", filename)
  7544. return
  7545. # Write
  7546. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  7547. f.close()
  7548. # verification of the saved project
  7549. # Open and parse
  7550. try:
  7551. saved_f = open(filename, 'r')
  7552. except IOError:
  7553. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  7554. return
  7555. try:
  7556. saved_d = json.load(saved_f, object_hook=dict2obj)
  7557. except:
  7558. self.inform.emit(
  7559. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  7560. f.close()
  7561. return
  7562. saved_f.close()
  7563. if 'version' in saved_d:
  7564. self.inform.emit(_("[success] Project saved to: %s") % filename)
  7565. else:
  7566. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  7567. settings = QSettings("Open Source", "FlatCAM")
  7568. lock_state = self.ui.lock_action.isChecked()
  7569. settings.setValue('toolbar_lock', lock_state)
  7570. # This will write the setting to the platform specific storage.
  7571. del settings
  7572. # if quit:
  7573. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  7574. # t.start()
  7575. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  7576. def start_delayed_quit(self, delay, filename, should_quit=None):
  7577. """
  7578. :param delay: period of checking if project file size is more than zero; in seconds
  7579. :param filename: the name of the project file to be checked periodically for size more than zero
  7580. :param should_quit: if the task finished will be followed by an app quit; boolean
  7581. :return:
  7582. """
  7583. to_quit = should_quit
  7584. self.save_timer = QtCore.QTimer()
  7585. self.save_timer.setInterval(delay)
  7586. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  7587. self.save_timer.start()
  7588. def check_project_file_size(self, filename, should_quit=None):
  7589. """
  7590. :param filename: the name of the project file to be checked periodically for size more than zero
  7591. :param should_quit: will quit the app if True; boolean
  7592. :return:
  7593. """
  7594. try:
  7595. if os.stat(filename).st_size > 0:
  7596. self.save_in_progress = False
  7597. self.save_timer.stop()
  7598. if should_quit:
  7599. self.app_quit.emit()
  7600. except Exception as e:
  7601. traceback.print_exc()
  7602. def on_options_app2project(self):
  7603. """
  7604. Callback for Options->Transfer Options->App=>Project. Copies options
  7605. from application defaults to project defaults.
  7606. :return: None
  7607. """
  7608. self.report_usage("on_options_app2project")
  7609. self.defaults_read_form()
  7610. self.options.update(self.defaults)
  7611. self.options_write_form()
  7612. def on_options_project2app(self):
  7613. """
  7614. Callback for Options->Transfer Options->Project=>App. Copies options
  7615. from project defaults to application defaults.
  7616. :return: None
  7617. """
  7618. self.report_usage("on_options_project2app")
  7619. self.options_read_form()
  7620. self.defaults.update(self.options)
  7621. self.defaults_write_form()
  7622. def on_options_project2object(self):
  7623. """
  7624. Callback for Options->Transfer Options->Project=>Object. Copies options
  7625. from project defaults to the currently selected object.
  7626. :return: None
  7627. """
  7628. self.report_usage("on_options_project2object")
  7629. self.options_read_form()
  7630. obj = self.collection.get_active()
  7631. if obj is None:
  7632. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7633. return
  7634. for option in self.options:
  7635. if option.find(obj.kind + "_") == 0:
  7636. oname = option[len(obj.kind) + 1:]
  7637. obj.options[oname] = self.options[option]
  7638. obj.to_form() # Update UI
  7639. def on_options_object2project(self):
  7640. """
  7641. Callback for Options->Transfer Options->Object=>Project. Copies options
  7642. from the currently selected object to project defaults.
  7643. :return: None
  7644. """
  7645. self.report_usage("on_options_object2project")
  7646. obj = self.collection.get_active()
  7647. if obj is None:
  7648. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7649. return
  7650. obj.read_form()
  7651. for option in obj.options:
  7652. if option in ['name']: # TODO: Handle this better...
  7653. continue
  7654. self.options[obj.kind + "_" + option] = obj.options[option]
  7655. self.options_write_form()
  7656. def on_options_object2app(self):
  7657. """
  7658. Callback for Options->Transfer Options->Object=>App. Copies options
  7659. from the currently selected object to application defaults.
  7660. :return: None
  7661. """
  7662. self.report_usage("on_options_object2app")
  7663. obj = self.collection.get_active()
  7664. if obj is None:
  7665. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7666. return
  7667. obj.read_form()
  7668. for option in obj.options:
  7669. if option in ['name']: # TODO: Handle this better...
  7670. continue
  7671. self.defaults[obj.kind + "_" + option] = obj.options[option]
  7672. self.defaults_write_form()
  7673. def on_options_app2object(self):
  7674. """
  7675. Callback for Options->Transfer Options->App=>Object. Copies options
  7676. from application defaults to the currently selected object.
  7677. :return: None
  7678. """
  7679. self.report_usage("on_options_app2object")
  7680. self.defaults_read_form()
  7681. obj = self.collection.get_active()
  7682. if obj is None:
  7683. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7684. return
  7685. for option in self.defaults:
  7686. if option.find(obj.kind + "_") == 0:
  7687. oname = option[len(obj.kind) + 1:]
  7688. obj.options[oname] = self.defaults[option]
  7689. obj.to_form() # Update UI
  7690. # end of file