FlatCAMApp.py 360 KB

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