FlatCAMApp.py 410 KB

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