FlatCAMApp.py 418 KB

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