FlatCAMApp.py 350 KB

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