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