FlatCAMApp.py 360 KB

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