FlatCAMApp.py 264 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500
  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 sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import tkinter as tk
  21. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  22. from PyQt5.QtCore import QSettings
  23. import time # Just used for debugging. Double check before removing.
  24. import urllib.request, urllib.parse, urllib.error
  25. import webbrowser
  26. from contextlib import contextmanager
  27. from xml.dom.minidom import parseString as parse_xml_string
  28. from copy import copy,deepcopy
  29. import numpy as np
  30. from datetime import datetime
  31. import gc
  32. ########################################
  33. ## Imports part of FlatCAM ##
  34. ########################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from PlotCanvas import *
  38. from FlatCAMGUI import *
  39. from FlatCAMCommon import LoudDict
  40. from FlatCAMPostProc import load_postprocessors
  41. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. from multiprocessing import Pool
  49. import tclCommands
  50. # from ParseFont import *
  51. ########################################
  52. ## App ##
  53. ########################################
  54. class App(QtCore.QObject):
  55. """
  56. The main application class. The constructor starts the GUI.
  57. """
  58. # Get Cmd Line Options
  59. cmd_line_shellfile = ''
  60. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  61. try:
  62. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  63. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  64. except getopt.GetoptError:
  65. print(cmd_line_help)
  66. sys.exit(2)
  67. for opt, arg in cmd_line_options:
  68. if opt == '-h':
  69. print(cmd_line_help)
  70. sys.exit()
  71. elif opt == '--shellfile':
  72. cmd_line_shellfile = arg
  73. # Logging ##
  74. log = logging.getLogger('base')
  75. log.setLevel(logging.DEBUG)
  76. # log.setLevel(logging.WARNING)
  77. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  78. handler = logging.StreamHandler()
  79. handler.setFormatter(formatter)
  80. log.addHandler(handler)
  81. # Version
  82. version = 8.906
  83. version_date = "2019/02/2"
  84. beta = True
  85. # URL for update checks and statistics
  86. version_url = "http://flatcam.org/version"
  87. # App URL
  88. app_url = "http://flatcam.org"
  89. # Manual URL
  90. manual_url = "http://flatcam.org/manual/index.html"
  91. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  92. should_we_quit = True
  93. ##################
  94. ## Signals ##
  95. ##################
  96. # Inform the user
  97. # Handled by:
  98. # * App.info() --> Print on the status bar
  99. inform = QtCore.pyqtSignal(str)
  100. # General purpose background task
  101. worker_task = QtCore.pyqtSignal(dict)
  102. # File opened
  103. # Handled by:
  104. # * register_folder()
  105. # * register_recent()
  106. # Note: Setting the parameters to unicode does not seem
  107. # to have an effect. Then are received as Qstring
  108. # anyway.
  109. # File type and filename
  110. file_opened = QtCore.pyqtSignal(str, str)
  111. # File type and filename
  112. file_saved = QtCore.pyqtSignal(str, str)
  113. # Percentage of progress
  114. progress = QtCore.pyqtSignal(int)
  115. plots_updated = QtCore.pyqtSignal()
  116. # Emitted by new_object() and passes the new object as argument, plot flag.
  117. # on_object_created() adds the object to the collection, plots on appropriate flag
  118. # and emits new_object_available.
  119. object_created = QtCore.pyqtSignal(object, bool, bool)
  120. # Emitted when a object has been changed (like scaled, mirrored)
  121. object_changed = QtCore.pyqtSignal(object)
  122. # Emitted after object has been plotted.
  123. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  124. object_plotted = QtCore.pyqtSignal(object)
  125. # Emitted when a new object has been added to the collection
  126. # and is ready to be used.
  127. new_object_available = QtCore.pyqtSignal(object)
  128. message = QtCore.pyqtSignal(str, str, str)
  129. # Emmited when shell command is finished(one command only)
  130. shell_command_finished = QtCore.pyqtSignal(object)
  131. # Emitted when multiprocess pool has been recreated
  132. pool_recreated = QtCore.pyqtSignal(object)
  133. # Emitted when an unhandled exception happens
  134. # in the worker task.
  135. thread_exception = QtCore.pyqtSignal(object)
  136. def __init__(self, user_defaults=True, post_gui=None):
  137. """
  138. Starts the application.
  139. :return: app
  140. :rtype: App
  141. """
  142. App.log.info("FlatCAM Starting...")
  143. ###################
  144. ### OS-specific ###
  145. ###################
  146. # Folder for user settings.
  147. if sys.platform == 'win32':
  148. from win32com.shell import shell, shellcon
  149. if platform.architecture()[0] == '32bit':
  150. App.log.debug("Win32!")
  151. else:
  152. App.log.debug("Win64!")
  153. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  154. '\FlatCAM'
  155. self.os = 'windows'
  156. else: # Linux/Unix/MacOS
  157. self.data_path = os.path.expanduser('~') + \
  158. '/.FlatCAM'
  159. self.os = 'unix'
  160. ###############################
  161. ### Setup folders and files ###
  162. ###############################
  163. if not os.path.exists(self.data_path):
  164. os.makedirs(self.data_path)
  165. App.log.debug('Created data folder: ' + self.data_path)
  166. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  167. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  168. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  169. if not os.path.exists(self.postprocessorpaths):
  170. os.makedirs(self.postprocessorpaths)
  171. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  172. # create current_defaults.FlatConfig file if there is none
  173. try:
  174. f = open(self.data_path + '/current_defaults.FlatConfig')
  175. f.close()
  176. except IOError:
  177. App.log.debug('Creating empty current_defaults.FlatConfig')
  178. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  179. json.dump({}, f)
  180. f.close()
  181. # create factory_defaults.FlatConfig file if there is none
  182. try:
  183. f = open(self.data_path + '/factory_defaults.FlatConfig')
  184. f.close()
  185. except IOError:
  186. App.log.debug('Creating empty factory_defaults.FlatConfig')
  187. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  188. json.dump({}, f)
  189. f.close()
  190. try:
  191. f = open(self.data_path + '/recent.json')
  192. f.close()
  193. except IOError:
  194. App.log.debug('Creating empty recent.json')
  195. f = open(self.data_path + '/recent.json', 'w')
  196. json.dump([], f)
  197. f.close()
  198. # Application directory. CHDIR to it. Otherwise, trying to load
  199. # GUI icons will fail as their path is relative.
  200. # This will fail under cx_freeze ...
  201. self.app_home = os.path.dirname(os.path.realpath(__file__))
  202. App.log.debug("Application path is " + self.app_home)
  203. App.log.debug("Started in " + os.getcwd())
  204. # cx_freeze workaround
  205. if os.path.isfile(self.app_home):
  206. self.app_home = os.path.dirname(self.app_home)
  207. os.chdir(self.app_home)
  208. # Create multiprocessing pool
  209. self.pool = Pool()
  210. ####################
  211. ## Initialize GUI ##
  212. ####################
  213. # FlatCAM colors used in plotting
  214. self.FC_light_green = '#BBF268BF'
  215. self.FC_dark_green = '#006E20BF'
  216. self.FC_light_blue = '#a5a5ffbf'
  217. self.FC_dark_blue = '#0000ffbf'
  218. QtCore.QObject.__init__(self)
  219. self.ui = FlatCAMGUI(self.version, self.beta, self)
  220. # self.connect(self.ui,
  221. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  222. # self.save_geometry) PyQt4
  223. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  224. self.ui.final_save.connect(self.final_save)
  225. ##############
  226. #### Data ####
  227. ##############
  228. self.recent = []
  229. self.clipboard = QtWidgets.QApplication.clipboard()
  230. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  231. self.project_filename = None
  232. self.toggle_units_ignore = False
  233. # self.defaults_form = PreferencesUI()
  234. self.general_defaults_form = GeneralPreferencesUI()
  235. self.gerber_defaults_form = GerberPreferencesUI()
  236. self.excellon_defaults_form = ExcellonPreferencesUI()
  237. self.geometry_defaults_form = GeometryPreferencesUI()
  238. self.cncjob_defaults_form = CNCJobPreferencesUI()
  239. self.tools_defaults_form = ToolsPreferencesUI()
  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. "units": self.general_defaults_form.general_app_group.units_radio,
  244. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  245. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  246. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  247. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  248. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  249. "global_snap_max": self.general_defaults_form.general_gui_group.snap_max_dist_entry,
  250. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  251. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  252. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  253. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  254. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  255. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  256. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  257. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  258. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  259. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  260. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  261. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  262. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  263. "gerber_plot": self.gerber_defaults_form.gerber_gen_group.plot_cb,
  264. "gerber_solid": self.gerber_defaults_form.gerber_gen_group.solid_cb,
  265. "gerber_multicolored": self.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  266. "gerber_circle_steps": self.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  267. "gerber_isotooldia": self.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  268. "gerber_isopasses": self.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  269. "gerber_isooverlap": self.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  270. "gerber_combine_passes": self.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  271. "gerber_milling_type": self.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  272. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  273. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  274. "gerber_bboxmargin": self.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  275. "gerber_bboxrounded": self.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  276. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  277. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  278. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  279. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  280. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  281. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  282. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  283. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  284. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  285. "excellon_search_time": self.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  286. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  287. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  288. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  289. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_opt_group.feedrate_rapid_entry,
  290. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  291. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  292. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  293. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  294. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  295. "excellon_toolchangexy": self.excellon_defaults_form.excellon_opt_group.toolchangexy_entry,
  296. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  297. "excellon_f_plunge": self.excellon_defaults_form.excellon_opt_group.fplunge_cb,
  298. "excellon_startz": self.excellon_defaults_form.excellon_opt_group.estartz_entry,
  299. "excellon_endz": self.excellon_defaults_form.excellon_opt_group.eendz_entry,
  300. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  301. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  302. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  303. "geometry_plot": self.geometry_defaults_form.geometry_gen_group.plot_cb,
  304. "geometry_cnctooldia": self.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  305. "geometry_circle_steps": self.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  306. "geometry_segx": self.geometry_defaults_form.geometry_opt_group.segx_entry,
  307. "geometry_segy": self.geometry_defaults_form.geometry_opt_group.segy_entry,
  308. "geometry_cutz": self.geometry_defaults_form.geometry_opt_group.cutz_entry,
  309. "geometry_travelz": self.geometry_defaults_form.geometry_opt_group.travelz_entry,
  310. "geometry_feedrate": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  311. "geometry_feedrate_z": self.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  312. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_rapid_entry,
  313. "geometry_spindlespeed": self.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  314. "geometry_dwell": self.geometry_defaults_form.geometry_opt_group.dwell_cb,
  315. "geometry_dwelltime": self.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  316. "geometry_ppname_g": self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  317. "geometry_f_plunge": self.geometry_defaults_form.geometry_opt_group.fplunge_cb,
  318. "geometry_toolchange": self.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  319. "geometry_toolchangez": self.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  320. "geometry_toolchangexy": self.geometry_defaults_form.geometry_opt_group.toolchangexy_entry,
  321. "geometry_startz": self.geometry_defaults_form.geometry_opt_group.gstartz_entry,
  322. "geometry_endz": self.geometry_defaults_form.geometry_opt_group.gendz_entry,
  323. "geometry_multidepth": self.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  324. "geometry_depthperpass": self.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  325. "geometry_extracut": self.geometry_defaults_form.geometry_opt_group.extracut_cb,
  326. "cncjob_plot": self.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  327. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  328. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  329. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  330. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  331. "cncjob_prepend": self.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  332. "cncjob_append": self.cncjob_defaults_form.cncjob_opt_group.append_text,
  333. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  334. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  335. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  336. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  337. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  338. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  339. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  340. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  341. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  342. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  343. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  344. "tools_gaps_ff": self.tools_defaults_form.tools_cutout_group.gaps_combo,
  345. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  346. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  347. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  348. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  349. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  350. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  351. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb,
  352. "tools_2sided_mirror_axis": self.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  353. "tools_2sided_axis_loc": self.tools_defaults_form.tools_2sided_group.axis_location_radio,
  354. "tools_2sided_drilldia": self.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  355. }
  356. # loads postprocessors
  357. self.postprocessors = load_postprocessors(self)
  358. for name in list(self.postprocessors.keys()):
  359. self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  360. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  361. if name == 'hpgl':
  362. continue
  363. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  364. self.defaults = LoudDict()
  365. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  366. self.defaults.update({
  367. "global_serial": 0,
  368. "global_stats": {},
  369. "units": "IN",
  370. "global_version_check": True,
  371. "global_send_stats": True,
  372. "global_gridx": 1.0,
  373. "global_gridy": 1.0,
  374. "global_snap_max": 0.05,
  375. "global_plot_fill": '#BBF268BF',
  376. "global_plot_line": '#006E20BF',
  377. "global_sel_fill": '#a5a5ffbf',
  378. "global_sel_line": '#0000ffbf',
  379. "global_alt_sel_fill": '#BBF268BF',
  380. "global_alt_sel_line": '#006E20BF',
  381. "global_draw_color": '#FF0000',
  382. "global_sel_draw_color": '#0000FF',
  383. "global_pan_button": '2',
  384. "global_mselect_key": 'Control',
  385. # "global_pan_with_space_key": False,
  386. "global_workspace": False,
  387. "global_workspaceT": "A4P",
  388. "global_toolbar_view": 127,
  389. "global_background_timeout": 300000, # Default value is 5 minutes
  390. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  391. # (python trace only for unknown errors),
  392. # 1 = show trace(show trace allways),
  393. # 2 = (For the future).
  394. # Persistence
  395. "global_last_folder": None,
  396. "global_last_save_folder": None,
  397. # Default window geometry
  398. "global_def_win_x": 100,
  399. "global_def_win_y": 100,
  400. "global_def_win_w": 1024,
  401. "global_def_win_h": 650,
  402. # Constants...
  403. "global_defaults_save_period_ms": 20000, # Time between default saves.
  404. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  405. "global_shell_at_startup": False, # Show the shell at startup.
  406. "global_recent_limit": 10, # Max. items in recent list.
  407. "fit_key": '1',
  408. "zoom_out_key": '2',
  409. "zoom_in_key": '3',
  410. "grid_toggle_key": 'G',
  411. "zoom_ratio": 1.5,
  412. "global_point_clipboard_format": "(%.4f, %.4f)",
  413. "global_zdownrate": None,
  414. "gerber_plot": True,
  415. "gerber_solid": True,
  416. "gerber_multicolored": False,
  417. "gerber_isotooldia": 0.016,
  418. "gerber_isopasses": 1,
  419. "gerber_isooverlap": 0.15,
  420. "gerber_combine_passes": False,
  421. "gerber_milling_type": "cl",
  422. "gerber_noncoppermargin": 0.1,
  423. "gerber_noncopperrounded": False,
  424. "gerber_bboxmargin": 0.1,
  425. "gerber_bboxrounded": False,
  426. "gerber_circle_steps": 64,
  427. "gerber_use_buffer_for_union": True,
  428. "excellon_plot": True,
  429. "excellon_solid": True,
  430. "excellon_format_upper_in": 2,
  431. "excellon_format_lower_in": 4,
  432. "excellon_format_upper_mm": 3,
  433. "excellon_format_lower_mm": 3,
  434. "excellon_zeros": "L",
  435. "excellon_units": "INCH",
  436. "excellon_optimization_type": 'B',
  437. "excellon_search_time": 3,
  438. "excellon_drillz": -0.1,
  439. "excellon_travelz": 0.1,
  440. "excellon_feedrate": 3.0,
  441. "excellon_feedrate_rapid": 3.0,
  442. "excellon_spindlespeed": None,
  443. "excellon_dwell": False,
  444. "excellon_dwelltime": 1,
  445. "excellon_toolchange": False,
  446. "excellon_toolchangez": 1.0,
  447. "excellon_toolchangexy": "0.0, 0.0",
  448. "excellon_tooldia": 0.016,
  449. "excellon_slot_tooldia": 0.016,
  450. "excellon_startz": None,
  451. "excellon_endz": 2.0,
  452. "excellon_ppname_e": 'default',
  453. "excellon_f_plunge": False,
  454. "excellon_gcode_type": "drills",
  455. "geometry_plot": True,
  456. "geometry_segx": 0.0,
  457. "geometry_segy": 0.0,
  458. "geometry_cutz": -0.002,
  459. "geometry_travelz": 0.1,
  460. "geometry_toolchange": False,
  461. "geometry_toolchangez": 1.0,
  462. "geometry_toolchangexy": "0.0, 0.0",
  463. "geometry_startz": None,
  464. "geometry_endz": 2.0,
  465. "geometry_feedrate": 3.0,
  466. "geometry_feedrate_z": 3.0,
  467. "geometry_feedrate_rapid": 3.0,
  468. "geometry_cnctooldia": 0.016,
  469. "geometry_spindlespeed": None,
  470. "geometry_dwell": False,
  471. "geometry_dwelltime": 1,
  472. "geometry_ppname_g": 'default',
  473. "geometry_f_plunge": False,
  474. "geometry_depthperpass": 0.002,
  475. "geometry_multidepth": False,
  476. "geometry_extracut": False,
  477. "geometry_circle_steps": 64,
  478. "cncjob_plot": True,
  479. "cncjob_tooldia": 0.0393701,
  480. "cncjob_coords_decimals": 4,
  481. "cncjob_fr_decimals": 2,
  482. "cncjob_prepend": "",
  483. "cncjob_append": "",
  484. "cncjob_steps_per_circle": 64,
  485. "tools_ncctools": "1.0, 0.5",
  486. "tools_nccoverlap": 0.4,
  487. "tools_nccmargin": 0.1,
  488. "tools_nccmethod": "seed",
  489. "tools_nccconnect": True,
  490. "tools_ncccontour": True,
  491. "tools_nccrest": False,
  492. "tools_cutouttooldia": 0.1,
  493. "tools_cutoutmargin": 0.1,
  494. "tools_cutoutgapsize": 0.15,
  495. "tools_gaps_rect": "4",
  496. "tools_gaps_ff": "8",
  497. "tools_painttooldia": 0.07,
  498. "tools_paintoverlap": 0.15,
  499. "tools_paintmargin": 0.0,
  500. "tools_paintmethod": "seed",
  501. "tools_selectmethod": "single",
  502. "tools_pathconnect": True,
  503. "tools_paintcontour": True,
  504. "tools_2sided_mirror_axis": "X",
  505. "tools_2sided_axis_loc": "point",
  506. "tools_2sided_drilldia": 1,
  507. })
  508. ###############################
  509. ### Load defaults from file ###
  510. if user_defaults:
  511. self.load_defaults(filename='current_defaults')
  512. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  513. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  514. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  515. self.save_defaults(silent=True)
  516. self.propagate_defaults(silent=True)
  517. self.restore_main_win_geom()
  518. def auto_save_defaults():
  519. try:
  520. self.save_defaults(silent=True)
  521. self.propagate_defaults(silent=True)
  522. finally:
  523. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  524. # the following lines activates automatic defaults save
  525. # if user_defaults:
  526. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  527. # self.options_form = PreferencesUI()
  528. self.general_options_form = GeneralPreferencesUI()
  529. self.gerber_options_form = GerberPreferencesUI()
  530. self.excellon_options_form = ExcellonPreferencesUI()
  531. self.geometry_options_form = GeometryPreferencesUI()
  532. self.cncjob_options_form = CNCJobPreferencesUI()
  533. self.tools_options_form = ToolsPreferencesUI()
  534. self.options_form_fields = {
  535. "units": self.general_options_form.general_app_group.units_radio,
  536. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  537. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  538. "global_snap_max": self.general_options_form.general_gui_group.snap_max_dist_entry,
  539. "gerber_plot": self.gerber_options_form.gerber_gen_group.plot_cb,
  540. "gerber_solid": self.gerber_options_form.gerber_gen_group.solid_cb,
  541. "gerber_multicolored": self.gerber_options_form.gerber_gen_group.multicolored_cb,
  542. "gerber_isotooldia": self.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  543. "gerber_isopasses": self.gerber_options_form.gerber_opt_group.iso_width_entry,
  544. "gerber_isooverlap": self.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  545. "gerber_combine_passes": self.gerber_options_form.gerber_opt_group.combine_passes_cb,
  546. "gerber_noncoppermargin": self.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  547. "gerber_noncopperrounded": self.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  548. "gerber_bboxmargin": self.gerber_options_form.gerber_opt_group.bbmargin_entry,
  549. "gerber_bboxrounded": self.gerber_options_form.gerber_opt_group.bbrounded_cb,
  550. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  551. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  552. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  553. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  554. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  555. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  556. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  557. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  558. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  559. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  560. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  561. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  562. "excellon_feedrate_rapid": self.excellon_options_form.excellon_opt_group.feedrate_rapid_entry,
  563. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  564. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  565. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  566. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  567. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  568. "excellon_toolchangexy": self.excellon_options_form.excellon_opt_group.toolchangexy_entry,
  569. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  570. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  571. "excellon_f_plunge": self.excellon_options_form.excellon_opt_group.fplunge_cb,
  572. "excellon_startz": self.excellon_options_form.excellon_opt_group.estartz_entry,
  573. "excellon_endz": self.excellon_options_form.excellon_opt_group.eendz_entry,
  574. "geometry_plot": self.geometry_options_form.geometry_gen_group.plot_cb,
  575. "geometry_cnctooldia": self.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  576. "geometry_segx": self.geometry_options_form.geometry_opt_group.segx_entry,
  577. "geometry_segy": self.geometry_options_form.geometry_opt_group.segy_entry,
  578. "geometry_cutz": self.geometry_options_form.geometry_opt_group.cutz_entry,
  579. "geometry_travelz": self.geometry_options_form.geometry_opt_group.travelz_entry,
  580. "geometry_feedrate": self.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  581. "geometry_feedrate_z": self.geometry_options_form.geometry_opt_group.cncplunge_entry,
  582. "geometry_feedrate_rapid": self.geometry_options_form.geometry_opt_group.cncfeedrate_rapid_entry,
  583. "geometry_spindlespeed": self.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  584. "geometry_dwell": self.geometry_options_form.geometry_opt_group.dwell_cb,
  585. "geometry_dwelltime": self.geometry_options_form.geometry_opt_group.dwelltime_entry,
  586. "geometry_ppname_g": self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  587. "geometry_f_plunge": self.geometry_options_form.geometry_opt_group.fplunge_cb,
  588. "geometry_toolchange": self.geometry_options_form.geometry_opt_group.toolchange_cb,
  589. "geometry_toolchangez": self.geometry_options_form.geometry_opt_group.toolchangez_entry,
  590. "geometry_toolchangexy": self.geometry_options_form.geometry_opt_group.toolchangexy_entry,
  591. "geometry_startz": self.geometry_options_form.geometry_opt_group.gstartz_entry,
  592. "geometry_endz": self.geometry_options_form.geometry_opt_group.gendz_entry,
  593. "geometry_depthperpass": self.geometry_options_form.geometry_opt_group.depthperpass_entry,
  594. "geometry_multidepth": self.geometry_options_form.geometry_opt_group.multidepth_cb,
  595. "geometry_extracut": self.geometry_options_form.geometry_opt_group.extracut_cb,
  596. "cncjob_plot": self.cncjob_options_form.cncjob_gen_group.plot_cb,
  597. "cncjob_tooldia": self.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  598. "cncjob_prepend": self.cncjob_options_form.cncjob_opt_group.prepend_text,
  599. "cncjob_append": self.cncjob_options_form.cncjob_opt_group.append_text,
  600. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  601. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  602. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  603. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  604. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  605. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  606. "tools_gaps_rect": self.tools_options_form.tools_cutout_group.gaps_radio,
  607. "tools_gaps_ff": self.tools_options_form.tools_cutout_group.gaps_combo,
  608. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  609. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  610. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  611. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  612. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  613. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  614. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb,
  615. "tools_2sided_mirror_axis": self.tools_options_form.tools_2sided_group.mirror_axis_radio,
  616. "tools_2sided_axis_loc": self.tools_options_form.tools_2sided_group.axis_location_radio,
  617. "tools_2sided_drilldia": self.tools_options_form.tools_2sided_group.drill_dia_entry
  618. }
  619. for name in list(self.postprocessors.keys()):
  620. self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  621. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  622. self.options = LoudDict()
  623. self.options.set_change_callback(self.on_options_dict_change)
  624. self.options.update({
  625. "units": "IN",
  626. "global_gridx": 1.0,
  627. "global_gridy": 1.0,
  628. "global_snap_max": 0.05,
  629. "global_background_timeout": 300000, # Default value is 5 minutes
  630. "global_verbose_error_level": 0, # Shell verbosity:
  631. # 0 = default(python trace only for unknown errors),
  632. # 1 = show trace(show trace allways), 2 = (For the future).
  633. "gerber_plot": True,
  634. "gerber_solid": True,
  635. "gerber_multicolored": False,
  636. "gerber_isotooldia": 0.016,
  637. "gerber_isopasses": 1,
  638. "gerber_isooverlap": 0.15,
  639. "gerber_combine_passes": True,
  640. "gerber_noncoppermargin": 0.0,
  641. "gerber_noncopperrounded": False,
  642. "gerber_bboxmargin": 0.0,
  643. "gerber_bboxrounded": False,
  644. "excellon_plot": True,
  645. "excellon_solid": False,
  646. "excellon_format_upper_in": 2,
  647. "excellon_format_lower_in": 4,
  648. "excellon_format_upper_mm": 3,
  649. "excellon_format_lower_mm": 3,
  650. "excellon_units": 'INCH',
  651. "excellon_optimization_type": 'B',
  652. "excellon_search_time": 3,
  653. "excellon_zeros": "L",
  654. "excellon_drillz": -0.1,
  655. "excellon_travelz": 0.1,
  656. "excellon_feedrate": 3.0,
  657. "excellon_feedrate_rapid": 3.0,
  658. "excellon_spindlespeed": None,
  659. "excellon_dwell": True,
  660. "excellon_dwelltime": 1000,
  661. "excellon_toolchange": False,
  662. "excellon_toolchangez": 1.0,
  663. "excellon_toolchangexy": "0.0, 0.0",
  664. "excellon_tooldia": 0.016,
  665. "excellon_ppname_e": 'default',
  666. "excellon_f_plunge": False,
  667. "excellon_startz": None,
  668. "excellon_endz": 2.0,
  669. "geometry_plot": True,
  670. "geometry_segx": 0.0,
  671. "geometry_segy": 0.0,
  672. "geometry_cutz": -0.002,
  673. "geometry_travelz": 0.1,
  674. "geometry_feedrate": 3.0,
  675. "geometry_feedrate_z": 3.0,
  676. "geometry_feedrate_rapid": 3.0,
  677. "geometry_spindlespeed": None,
  678. "geometry_dwell": True,
  679. "geometry_dwelltime": 1000,
  680. "geometry_cnctooldia": 0.016,
  681. "geometry_toolchange": False,
  682. "geometry_toolchangez": 2.0,
  683. "geometry_toolchangexy": "0.0, 0.0",
  684. "geometry_startz": None,
  685. "geometry_endz": 2.0,
  686. "geometry_ppname_g": "default",
  687. "geometry_f_plunge": False,
  688. "geometry_depthperpass": 0.002,
  689. "geometry_multidepth": False,
  690. "geometry_extracut": False,
  691. "cncjob_plot": True,
  692. "cncjob_tooldia": 0.016,
  693. "cncjob_prepend": "",
  694. "cncjob_append": "",
  695. "tools_ncctools": "1.0, 0.5",
  696. "tools_nccoverlap": 0.4,
  697. "tools_nccmargin": 1,
  698. "tools_cutouttooldia": 0.07,
  699. "tools_cutoutmargin": 0.1,
  700. "tools_cutoutgapsize": 0.15,
  701. "tools_gaps_rect": "4",
  702. "tools_gaps_ff": "8",
  703. "tools_painttooldia": 0.07,
  704. "tools_paintoverlap": 0.15,
  705. "tools_paintmargin": 0.0,
  706. "tools_paintmethod": "seed",
  707. "tools_selectmethod": "single",
  708. "tools_pathconnect": True,
  709. "tools_paintcontour": True,
  710. "tools_2sided_mirror_axis": "X",
  711. "tools_2sided_axis_loc": 'point',
  712. "tools_2sided_drilldia": 1
  713. })
  714. self.options.update(self.defaults) # Copy app defaults to project options
  715. self.gen_form = None
  716. self.ger_form = None
  717. self.exc_form = None
  718. self.geo_form = None
  719. self.cnc_form = None
  720. self.tools_form = None
  721. self.on_options_combo_change(0) # Will show the initial form
  722. ### Define OBJECT COLLECTION ###
  723. self.collection = ObjectCollection(self)
  724. self.ui.project_tab_layout.addWidget(self.collection.view)
  725. ###
  726. self.log.debug("Finished creating Object Collection.")
  727. ### Initialize the color box's color in Preferences -> Global -> Color
  728. # Init Plot Colors
  729. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  730. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  731. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  732. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  733. int(self.defaults['global_plot_fill'][7:9], 16))
  734. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  735. int(self.defaults['global_plot_fill'][7:9], 16))
  736. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  737. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  738. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  739. # Init Left-Right Selection colors
  740. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  741. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  742. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  743. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  744. int(self.defaults['global_sel_fill'][7:9], 16))
  745. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  746. int(self.defaults['global_sel_fill'][7:9], 16))
  747. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  748. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  749. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  750. # Init Right-Left Selection colors
  751. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  752. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  753. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  754. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  755. int(self.defaults['global_sel_fill'][7:9], 16))
  756. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  757. int(self.defaults['global_sel_fill'][7:9], 16))
  758. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  759. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  760. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  761. # Init Draw color and Selection Draw Color
  762. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  763. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  764. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  765. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  766. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  767. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  768. #### End of Data ####
  769. #### Plot Area ####
  770. start_plot_time = time.time() # debug
  771. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  772. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  773. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  774. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  775. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  776. # Keys over plot enabled
  777. self.plotcanvas.vis_connect('key_press', self.on_key_over_plot)
  778. self.plotcanvas.vis_connect('key_release', self.on_key_release_over_plot)
  779. self.ui.splitter.setStretchFactor(1, 2)
  780. # So it can receive key presses
  781. self.plotcanvas.vispy_canvas.native.setFocus()
  782. self.app_cursor = self.plotcanvas.new_cursor()
  783. self.app_cursor.enabled = False
  784. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  785. # depending on from where those tools are called different actions can be done
  786. self.call_source = 'app'
  787. end_plot_time = time.time()
  788. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  789. ### EDITOR section
  790. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  791. self.exc_editor = FlatCAMExcEditor(self)
  792. #### Adjust tabs width ####
  793. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  794. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  795. self.collection.view.setMinimumWidth(290)
  796. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  797. #### Worker ####
  798. self.workers = WorkerStack()
  799. self.worker_task.connect(self.workers.add_task)
  800. ### Signal handling ###
  801. ## Custom signals
  802. self.inform.connect(self.info)
  803. self.message.connect(self.message_dialog)
  804. self.progress.connect(self.set_progress_bar)
  805. self.object_created.connect(self.on_object_created)
  806. self.object_changed.connect(self.on_object_changed)
  807. self.object_plotted.connect(self.on_object_plotted)
  808. self.plots_updated.connect(self.on_plots_updated)
  809. self.file_opened.connect(self.register_recent)
  810. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  811. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  812. ## Standard signals
  813. # Menu
  814. self.ui.menufilenew.triggered.connect(self.on_file_new_click)
  815. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  816. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  817. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  818. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  819. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  820. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  821. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  822. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  823. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  824. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  825. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  826. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  827. self.ui.menufileexportexcellon.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=None))
  828. self.ui.menufileexportexcellon_altium.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=True))
  829. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  830. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  831. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  832. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  833. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  834. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  835. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  836. self.ui.menueditnewexc.triggered.connect(self.new_excellon_object)
  837. self.ui.menueditedit.triggered.connect(self.object2editor)
  838. self.ui.menueditok.triggered.connect(self.editor2object)
  839. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  840. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  841. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  842. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  843. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  844. self.ui.menueditdelete.triggered.connect(self.on_delete)
  845. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  846. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  847. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  848. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  849. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  850. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  851. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  852. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  853. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  854. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  855. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  856. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  857. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  858. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  859. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  860. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  861. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  862. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  863. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  864. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  865. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  866. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  867. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  868. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  869. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  870. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  871. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  872. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  873. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  874. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  875. self.ui.menuhelp_about.triggered.connect(self.on_about)
  876. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  877. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  878. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  879. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  880. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  881. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  882. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  883. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  884. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  885. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  886. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  887. # Toolbar
  888. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  889. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  890. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  891. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  892. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  893. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  894. self.ui.replot_btn.triggered.connect(self.plot_all)
  895. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  896. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  897. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  898. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  899. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  900. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  901. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  902. self.ui.delete_btn.triggered.connect(self.on_delete)
  903. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  904. # Context Menu
  905. self.ui.popmenu_new_geo.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  906. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  907. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  908. self.ui.gridmenu_1.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.05"))
  909. self.ui.gridmenu_2.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.1"))
  910. self.ui.gridmenu_3.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.2"))
  911. self.ui.gridmenu_4.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.5"))
  912. self.ui.gridmenu_5.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("1.0"))
  913. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  914. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  915. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  916. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  917. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  918. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  919. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  920. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  921. self.ui.clearplot.triggered.connect(self.clear_plots)
  922. self.ui.replot.triggered.connect(self.plot_all)
  923. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  924. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  925. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  926. self.ui.popmenu_save.triggered.connect(self.editor2object)
  927. self.ui.popmenu_move.triggered.connect(self.obj_move)
  928. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  929. # Preferences Plot Area TAB
  930. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  931. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  932. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  933. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  934. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  935. ###############################
  936. ### GUI PREFERENCES SIGNALS ###
  937. ###############################
  938. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  939. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  940. ###############################
  941. ### GUI PREFERENCES SIGNALS ###
  942. ###############################
  943. # Setting plot colors signals
  944. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  945. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  946. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  947. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  948. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  949. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  950. # Setting selection (left - right) colors signals
  951. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  952. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  953. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  954. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  955. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  956. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  957. # Setting selection (right - left) colors signals
  958. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  959. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  960. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  961. self.on_alt_sf_color_spinner)
  962. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  963. self.on_alt_sf_color_slider)
  964. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  965. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  966. # Setting Editor Draw colors signals
  967. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  968. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  969. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  970. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  971. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  972. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  973. self.general_defaults_form.general_gui_group.theme_combo.activated.connect(self.on_theme)
  974. # Modify G-CODE Plot Area TAB
  975. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  976. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  977. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  978. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  979. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  980. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  981. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  982. # Object list
  983. self.collection.view.activated.connect(self.on_row_activated)
  984. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  985. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  986. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  987. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  988. self.on_excellon_defaults_button)
  989. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  990. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  991. self.on_excellon_options_button)
  992. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  993. self.tool_tab_locked = False
  994. ####################
  995. ### Other setups ###
  996. ####################
  997. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  998. self.setup_obj_classes()
  999. self.setup_recent_items()
  1000. self.setup_component_editor()
  1001. #############
  1002. ### Shell ###
  1003. #############
  1004. ###
  1005. # Auto-complete KEYWORDS
  1006. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1007. 'aligndrill', 'clear',
  1008. 'aligndrillgrid', 'cncjob', 'cutout', 'cutout_any', 'delete', 'drillcncjob',
  1009. 'export_gcode',
  1010. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1011. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1012. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1013. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1014. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1015. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1016. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1017. ]
  1018. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1019. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1020. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1021. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1022. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1023. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1024. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1025. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1026. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1027. ]
  1028. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1029. self.shell = FCShell(self, version=self.version)
  1030. self.shell._edit.set_model_data(self.myKeywords)
  1031. self.shell.setWindowIcon(self.ui.app_icon)
  1032. self.shell.setWindowTitle("FlatCAM Shell")
  1033. self.shell.resize(*self.defaults["global_shell_shape"])
  1034. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1035. self.shell.append_output("(Type help to get started)\n\n")
  1036. self.init_tcl()
  1037. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1038. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1039. self.ui.shell_dock.setWidget(self.shell)
  1040. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1041. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1042. QtWidgets.QDockWidget.DockWidgetFloatable |
  1043. QtWidgets.QDockWidget.DockWidgetClosable)
  1044. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1045. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1046. if self.defaults["global_shell_at_startup"]:
  1047. self.ui.shell_dock.show()
  1048. else:
  1049. self.ui.shell_dock.hide()
  1050. #########################
  1051. ### Tools and Plugins ###
  1052. #########################
  1053. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1054. self.install_tools()
  1055. ### System Font Parsing ###
  1056. # self.f_parse = ParseFont(self)
  1057. # self.parse_system_fonts()
  1058. # test if the program was started with a script as parameter
  1059. if self.cmd_line_shellfile:
  1060. try:
  1061. with open(self.cmd_line_shellfile, "r") as myfile:
  1062. cmd_line_shellfile_text = myfile.read()
  1063. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1064. except Exception as ext:
  1065. print("ERROR: ", ext)
  1066. sys.exit(2)
  1067. ###########################
  1068. #### Check for updates ####
  1069. ###########################
  1070. # Separate thread (Not worker)
  1071. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1072. if (self.beta is False or self.beta is None) and \
  1073. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1074. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1075. self.thr2 = QtCore.QThread()
  1076. self.worker_task.emit({'fcn': self.version_check,
  1077. 'params': []})
  1078. self.thr2.start()
  1079. ####################################
  1080. #### Variables for global usage ####
  1081. ####################################
  1082. # coordinates for relative position display
  1083. self.rel_point1 = (0, 0)
  1084. self.rel_point2 = (0, 0)
  1085. # variable to store coordinates
  1086. self.pos = (0, 0)
  1087. self.pos_jump = (0, 0)
  1088. # variable to store if there was motion before right mouse button click (panning)
  1089. self.panning_action = False
  1090. # variable to store if a command is active (then the var is not None) and which one it is
  1091. self.command_active = None
  1092. # variable to store the status of moving selection action
  1093. # None value means that it's not an selection action
  1094. # True value = a selection from left to right
  1095. # False value = a selection from right to left
  1096. self.selection_type = None
  1097. # List to store the objects that are currently loaded in FlatCAM
  1098. # This list is updated on each object creation or object delete
  1099. self.all_objects_list = []
  1100. # List to store the objects that are selected
  1101. self.sel_objects_list = []
  1102. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1103. self.key_modifiers = None
  1104. # Variable to hold the status of the axis
  1105. self.toggle_axis = True
  1106. # Variable to store the status of the fullscreen event
  1107. self.toggle_fscreen = False
  1108. self.cursor = None
  1109. # Variable to store the GCODE that was edited
  1110. self.gcode_edited = ""
  1111. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1112. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1113. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1114. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1115. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1116. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1117. 'mpf']
  1118. self.svg_list = ['svg']
  1119. self.dxf_list = ['dxf']
  1120. self.prj_list = ['flatprj']
  1121. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1122. # flag for polygons not cleared
  1123. self.poly_not_cleared = False
  1124. ### Save defaults to factory_defaults.FlatConfig file ###
  1125. ### It's done only once after install #############
  1126. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1127. fac_def_from_file = factory_file.read()
  1128. factory_defaults = json.loads(fac_def_from_file)
  1129. # if the file contain an empty dictionary then save the factory defaults into the file
  1130. if not factory_defaults:
  1131. self.save_factory_defaults(silent=False)
  1132. factory_file.close()
  1133. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1134. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1135. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1136. # Post-GUI initialization: Experimental attempt
  1137. # to perform unit tests on the GUI.
  1138. # if post_gui is not None:
  1139. # post_gui(self)
  1140. App.log.debug("END of constructor. Releasing control.")
  1141. # accept a project file as command line parameter
  1142. # the path/file_name must be enclosed in quotes if it contain spaces
  1143. for argument in App.args:
  1144. if '.FlatPrj' in argument:
  1145. try:
  1146. project_name = str(argument)
  1147. if project_name == "":
  1148. self.inform.emit("Open cancelled.")
  1149. else:
  1150. # self.open_project(project_name)
  1151. run_from_arg = True
  1152. self.worker_task.emit({'fcn': self.open_project,
  1153. 'params': [project_name, run_from_arg]})
  1154. except Exception as e:
  1155. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1156. def defaults_read_form(self):
  1157. for option in self.defaults_form_fields:
  1158. try:
  1159. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1160. except:
  1161. pass
  1162. def defaults_write_form(self):
  1163. for option in self.defaults:
  1164. self.defaults_write_form_field(option)
  1165. # try:
  1166. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1167. # except KeyError:
  1168. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1169. # # TODO: Rethink this?
  1170. # pass
  1171. def defaults_write_form_field(self, field):
  1172. try:
  1173. self.defaults_form_fields[field].set_value(self.defaults[field])
  1174. except KeyError:
  1175. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1176. # TODO: Rethink this?
  1177. pass
  1178. def clear_pool(self):
  1179. self.pool.close()
  1180. self.pool = Pool()
  1181. self.pool_recreated.emit(self.pool)
  1182. gc.collect()
  1183. # the order that the tools are installed is important as they can depend on each other install position
  1184. def install_tools(self):
  1185. self.dblsidedtool = DblSidedTool(self)
  1186. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1187. self.measurement_tool = Measurement(self)
  1188. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1189. self.panelize_tool = Panelize(self)
  1190. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1191. self.film_tool = Film(self)
  1192. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1193. self.move_tool = ToolMove(self)
  1194. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1195. before=self.ui.menueditorigin)
  1196. self.cutout_tool = ToolCutout(self)
  1197. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1198. before=self.measurement_tool.menuAction)
  1199. self.ncclear_tool = NonCopperClear(self)
  1200. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1201. before=self.measurement_tool.menuAction, separator=True)
  1202. self.paint_tool = ToolPaint(self)
  1203. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1204. before=self.measurement_tool.menuAction, separator=True)
  1205. self.calculator_tool = ToolCalculator(self)
  1206. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1207. self.transform_tool = ToolTransform(self)
  1208. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1209. self.properties_tool = Properties(self)
  1210. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1211. self.image_tool = ToolImage(self)
  1212. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1213. separator=True)
  1214. self.log.debug("Tools are installed.")
  1215. def init_tools(self):
  1216. # delete the data currently in the Tools Tab and the Tab itself
  1217. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1218. if widget is not None:
  1219. widget.deleteLater()
  1220. self.ui.notebook.removeTab(2)
  1221. # rebuild the Tools Tab
  1222. self.ui.tool_tab = QtWidgets.QWidget()
  1223. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1224. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1225. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1226. self.ui.tool_scroll_area = VerticalScrollArea()
  1227. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1228. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1229. self.install_tools()
  1230. self.log.debug("Tools are initialized.")
  1231. # def parse_system_fonts(self):
  1232. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1233. # 'params': []})
  1234. def object2editor(self):
  1235. """
  1236. Send the current Geometry or Excellon object (if any) into the editor.
  1237. :return: None
  1238. """
  1239. # adjust the visibility of some of the canvas context menu
  1240. self.ui.popmenu_edit.setVisible(False)
  1241. self.ui.popmenu_save.setVisible(True)
  1242. edited_object = self.collection.get_active()
  1243. if isinstance(edited_object, FlatCAMGeometry):
  1244. # for now, if the Geometry is MultiGeo do not allow the editing
  1245. if edited_object.multigeo is True:
  1246. self.inform.emit("[warning_notcl]Editing a MultiGeo Geometry is not possible for the moment.")
  1247. return
  1248. self.geo_editor.edit_fcgeometry(edited_object)
  1249. # set call source to the Editor we go into
  1250. self.call_source = 'geo_editor'
  1251. elif isinstance(edited_object, FlatCAMExcellon):
  1252. self.exc_editor.edit_fcexcellon(edited_object)
  1253. # set call source to the Editor we go into
  1254. self.call_source = 'exc_editor'
  1255. else:
  1256. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to edit.")
  1257. return
  1258. # make sure that we can't select another object while in Editor Mode:
  1259. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1260. # delete any selection shape that might be active as they are not relevant in Editor
  1261. self.delete_selection_shape()
  1262. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1263. self.ui.plot_tab_area.protectTab(0)
  1264. self.inform.emit("[warning_notcl]Editor is activated ...")
  1265. def editor2object(self):
  1266. """
  1267. Transfers the Geometry or Excellon from the editor to the current object.
  1268. :return: None
  1269. """
  1270. # adjust the visibility of some of the canvas context menu
  1271. self.ui.popmenu_edit.setVisible(True)
  1272. self.ui.popmenu_save.setVisible(False)
  1273. edited_obj = self.collection.get_active()
  1274. obj_type = ""
  1275. if isinstance(edited_obj, FlatCAMGeometry):
  1276. obj_type = "Geometry"
  1277. self.geo_editor.update_fcgeometry(edited_obj)
  1278. self.geo_editor.update_options(edited_obj)
  1279. self.geo_editor.deactivate()
  1280. # update the geo object options so it is including the bounding box values
  1281. try:
  1282. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1283. edited_obj.options['xmin'] = xmin
  1284. edited_obj.options['ymin'] = ymin
  1285. edited_obj.options['xmax'] = xmax
  1286. edited_obj.options['ymax'] = ymax
  1287. except AttributeError:
  1288. self.inform.emit("[warning] Object empty after edit.")
  1289. elif isinstance(edited_obj, FlatCAMExcellon):
  1290. obj_type = "Excellon"
  1291. self.exc_editor.update_fcexcellon(edited_obj)
  1292. self.exc_editor.deactivate()
  1293. # update the exc object options so it is including the bounding box values
  1294. try:
  1295. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1296. edited_obj.options['xmin'] = xmin
  1297. edited_obj.options['ymin'] = ymin
  1298. edited_obj.options['xmax'] = xmax
  1299. edited_obj.options['ymax'] = ymax
  1300. except AttributeError:
  1301. self.inform.emit("[warning] Object empty after edit.")
  1302. else:
  1303. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to update.")
  1304. return
  1305. # restore the call_source to app
  1306. self.call_source = 'app'
  1307. edited_obj.plot()
  1308. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1309. self.ui.plot_tab_area.protectTab(0)
  1310. self.inform.emit("[success] %s is updated, returning to App..." % obj_type)
  1311. # reset the Object UI to original settings
  1312. # edited_obj.set_ui(edited_obj.ui_type())
  1313. # edited_obj.build_ui()
  1314. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1315. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1316. def get_last_folder(self):
  1317. return self.defaults["global_last_folder"]
  1318. def get_last_save_folder(self):
  1319. return self.defaults["global_last_save_folder"]
  1320. def report_usage(self, resource):
  1321. """
  1322. Increments usage counter for the given resource
  1323. in self.defaults['global_stats'].
  1324. :param resource: Name of the resource.
  1325. :return: None
  1326. """
  1327. if resource in self.defaults['global_stats']:
  1328. self.defaults['global_stats'][resource] += 1
  1329. else:
  1330. self.defaults['global_stats'][resource] = 1
  1331. def init_tcl(self):
  1332. if hasattr(self,'tcl'):
  1333. # self.tcl = None
  1334. # TODO we need to clean non default variables and procedures here
  1335. # new object cannot be used here as it will not remember values created for next passes,
  1336. # because tcl was execudted in old instance of TCL
  1337. pass
  1338. else:
  1339. self.tcl = tk.Tcl()
  1340. self.setup_shell()
  1341. self.log.debug("TCL Shell has been initialized.")
  1342. # TODO: This shouldn't be here.
  1343. class TclErrorException(Exception):
  1344. """
  1345. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1346. """
  1347. pass
  1348. def shell_message(self, msg, show=False, error=False):
  1349. """
  1350. Shows a message on the FlatCAM Shell
  1351. :param msg: Message to display.
  1352. :param show: Opens the shell.
  1353. :param error: Shows the message as an error.
  1354. :return: None
  1355. """
  1356. if show:
  1357. self.ui.shell_dock.show()
  1358. try:
  1359. if error:
  1360. self.shell.append_error(msg + "\n")
  1361. else:
  1362. self.shell.append_output(msg + "\n")
  1363. except AttributeError:
  1364. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1365. def raise_tcl_unknown_error(self, unknownException):
  1366. """
  1367. Raise exception if is different type than TclErrorException
  1368. this is here mainly to show unknown errors inside TCL shell console.
  1369. :param unknownException:
  1370. :return:
  1371. """
  1372. if not isinstance(unknownException, self.TclErrorException):
  1373. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1374. else:
  1375. raise unknownException
  1376. def display_tcl_error(self, error, error_info=None):
  1377. """
  1378. escape bracket [ with \ otherwise there is error
  1379. "ERROR: missing close-bracket" instead of real error
  1380. :param error: it may be text or exception
  1381. :return: None
  1382. """
  1383. if isinstance(error, Exception):
  1384. exc_type, exc_value, exc_traceback = error_info
  1385. if not isinstance(error, self.TclErrorException):
  1386. show_trace = 1
  1387. else:
  1388. show_trace = int(self.defaults['global_verbose_error_level'])
  1389. if show_trace > 0:
  1390. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1391. trc_formated = []
  1392. for a in reversed(trc):
  1393. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1394. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1395. exc_type,
  1396. "\n".join(trc_formated))
  1397. else:
  1398. text = "%s" % error
  1399. else:
  1400. text = error
  1401. text = text.replace('[', '\\[').replace('"', '\\"')
  1402. self.tcl.eval('return -code error "%s"' % text)
  1403. def raise_tcl_error(self, text):
  1404. """
  1405. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1406. :param text: text of error
  1407. :return: raise exception
  1408. """
  1409. self.display_tcl_error(text)
  1410. raise self.TclErrorException(text)
  1411. def exec_command(self, text):
  1412. """
  1413. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1414. Also handles execution in separated threads
  1415. :param text:
  1416. :return: output if there was any
  1417. """
  1418. self.report_usage('exec_command')
  1419. result = self.exec_command_test(text, False)
  1420. #MS: added this method call so the geometry is updated once the TCL
  1421. #command is executed
  1422. self.plot_all()
  1423. return result
  1424. def exec_command_test(self, text, reraise=True):
  1425. """
  1426. Same as exec_command(...) with additional control over exceptions.
  1427. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1428. :param text: Input command
  1429. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1430. :return: Output from the command
  1431. """
  1432. text = str(text)
  1433. try:
  1434. self.shell.open_proccessing() # Disables input box.
  1435. result = self.tcl.eval(str(text))
  1436. if result != 'None':
  1437. self.shell.append_output(result + '\n')
  1438. except tk.TclError as e:
  1439. # This will display more precise answer if something in TCL shell fails
  1440. result = self.tcl.eval("set errorInfo")
  1441. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1442. self.shell.append_error('ERROR: ' + result + '\n')
  1443. # Show error in console and just return or in test raise exception
  1444. if reraise:
  1445. raise e
  1446. finally:
  1447. self.shell.close_proccessing()
  1448. pass
  1449. return result
  1450. # """
  1451. # Code below is unsused. Saved for later.
  1452. # """
  1453. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1454. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1455. # self.log.debug(parts)
  1456. # try:
  1457. # if parts[0] not in commands:
  1458. # self.shell.append_error("Unknown command\n")
  1459. # return
  1460. #
  1461. # #import inspect
  1462. # #inspect.getargspec(someMethod)
  1463. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1464. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1465. # self.shell.append_error(
  1466. # "Command %s takes %d arguments. %d given.\n" %
  1467. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1468. # )
  1469. # return
  1470. #
  1471. # cmdfcn = commands[parts[0]]["fcn"]
  1472. # cmdconv = commands[parts[0]]["converters"]
  1473. # if len(parts) - 1 > 0:
  1474. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1475. # else:
  1476. # retval = cmdfcn()
  1477. # retfcn = commands[parts[0]]["retfcn"]
  1478. # if retval and retfcn(retval):
  1479. # self.shell.append_output(retfcn(retval) + "\n")
  1480. #
  1481. # except Exception as e:
  1482. # #self.shell.append_error(''.join(traceback.format_exc()))
  1483. # #self.shell.append_error("?\n")
  1484. # self.shell.append_error(str(e) + "\n")
  1485. def info(self, msg):
  1486. """
  1487. Informs the user. Normally on the status bar, optionally
  1488. also on the shell.
  1489. :param msg: Text to write.
  1490. :return: None
  1491. """
  1492. # Type of message in brackets at the begining of the message.
  1493. match = re.search("\[([^\]]+)\](.*)", msg)
  1494. if match:
  1495. level = match.group(1)
  1496. msg_ = match.group(2)
  1497. self.ui.fcinfo.set_status(str(msg_), level=level)
  1498. if level == "error" or level == "warning":
  1499. self.shell_message(msg, error=True, show=True)
  1500. elif level == "error_notcl" or level == "warning_notcl":
  1501. self.shell_message(msg, error=True, show=False)
  1502. else:
  1503. self.shell_message(msg, error=False, show=False)
  1504. else:
  1505. self.ui.fcinfo.set_status(str(msg), level="info")
  1506. # make sure that if the message is to clear the infobar with a space
  1507. # is not printed over and over on the shell
  1508. if msg != '':
  1509. self.shell_message(msg)
  1510. def restore_toolbar_view(self):
  1511. tb = self.defaults["global_toolbar_view"]
  1512. if tb & 1:
  1513. self.ui.toolbarfile.setVisible(True)
  1514. else:
  1515. self.ui.toolbarfile.setVisible(False)
  1516. if tb & 2:
  1517. self.ui.toolbargeo.setVisible(True)
  1518. else:
  1519. self.ui.toolbargeo.setVisible(False)
  1520. if tb & 4:
  1521. self.ui.toolbarview.setVisible(True)
  1522. else:
  1523. self.ui.toolbarview.setVisible(False)
  1524. if tb & 8:
  1525. self.ui.toolbartools.setVisible(True)
  1526. else:
  1527. self.ui.toolbartools.setVisible(False)
  1528. if tb & 16:
  1529. self.ui.exc_edit_toolbar.setVisible(True)
  1530. else:
  1531. self.ui.exc_edit_toolbar.setVisible(False)
  1532. if tb & 32:
  1533. self.ui.geo_edit_toolbar.setVisible(True)
  1534. else:
  1535. self.ui.geo_edit_toolbar.setVisible(False)
  1536. if tb & 64:
  1537. self.ui.snap_toolbar.setVisible(True)
  1538. else:
  1539. self.ui.snap_toolbar.setVisible(False)
  1540. def load_defaults(self, filename):
  1541. """
  1542. Loads the aplication's default settings from current_defaults.FlatConfig into
  1543. ``self.defaults``.
  1544. :return: None
  1545. """
  1546. try:
  1547. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1548. options = f.read()
  1549. f.close()
  1550. except IOError:
  1551. self.log.error("Could not load defaults file.")
  1552. self.inform.emit("[error] Could not load defaults file.")
  1553. # in case the defaults file can't be loaded, show all toolbars
  1554. self.defaults["global_toolbar_view"] = 127
  1555. return
  1556. try:
  1557. defaults = json.loads(options)
  1558. except:
  1559. # in case the defaults file can't be loaded, show all toolbars
  1560. self.defaults["global_toolbar_view"] = 127
  1561. e = sys.exc_info()[0]
  1562. App.log.error(str(e))
  1563. self.inform.emit("[error] Failed to parse defaults file.")
  1564. return
  1565. self.defaults.update(defaults)
  1566. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1567. # restore the toolbar view
  1568. self.restore_toolbar_view()
  1569. def on_import_preferences(self):
  1570. """
  1571. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1572. ``self.defaults``.
  1573. :return: None
  1574. """
  1575. self.report_usage("on_import_preferences")
  1576. App.log.debug("on_import_preferences()")
  1577. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1578. try:
  1579. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1580. directory=self.data_path, filter=filter)
  1581. except TypeError:
  1582. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1583. filename = str(filename)
  1584. if filename == "":
  1585. self.inform.emit("[warning_notcl]FlatCAM preferences import cancelled.")
  1586. else:
  1587. try:
  1588. f = open(filename)
  1589. options = f.read()
  1590. f.close()
  1591. except IOError:
  1592. self.log.error("Could not load defaults file.")
  1593. self.inform.emit("[error_notcl] Could not load defaults file.")
  1594. return
  1595. try:
  1596. defaults_from_file = json.loads(options)
  1597. except:
  1598. e = sys.exc_info()[0]
  1599. App.log.error(str(e))
  1600. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1601. return
  1602. self.defaults.update(defaults_from_file)
  1603. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1604. def on_export_preferences(self):
  1605. self.report_usage("on_export_preferences")
  1606. App.log.debug("on_export_preferences()")
  1607. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1608. try:
  1609. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences",
  1610. directory=self.data_path, filter=filter)
  1611. except TypeError:
  1612. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1613. filename = str(filename)
  1614. defaults_from_file = {}
  1615. if filename == "":
  1616. self.inform.emit("[warning_notcl]FlatCAM preferences export cancelled.")
  1617. return
  1618. else:
  1619. try:
  1620. f = open(filename, 'w')
  1621. defaults_file_content = f.read()
  1622. f.close()
  1623. except IOError:
  1624. App.log.debug('Creating a new preferences file ...')
  1625. f = open(filename, 'w')
  1626. json.dump({}, f)
  1627. f.close()
  1628. except:
  1629. e = sys.exc_info()[0]
  1630. App.log.error("Could not load defaults file.")
  1631. App.log.error(str(e))
  1632. self.inform.emit("[error_notcl]Could not load defaults file.")
  1633. return
  1634. try:
  1635. defaults_from_file = json.loads(defaults_file_content)
  1636. except:
  1637. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1638. # Update options
  1639. self.defaults_read_form()
  1640. defaults_from_file.update(self.defaults)
  1641. self.propagate_defaults(silent=True)
  1642. # Save update options
  1643. try:
  1644. f = open(filename, "w")
  1645. json.dump(defaults_from_file, f)
  1646. f.close()
  1647. except:
  1648. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1649. return
  1650. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1651. def on_preferences_open_folder(self):
  1652. if sys.platform == 'win32':
  1653. subprocess.Popen('explorer %s' % self.data_path)
  1654. elif sys.platform == 'darwin':
  1655. os.system('open "%s"' % self.data_path)
  1656. else:
  1657. subprocess.Popen(['xdg-open', self.data_path])
  1658. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1659. def save_geometry(self, x, y, width, height, notebook_width):
  1660. self.defaults["global_def_win_x"] = x
  1661. self.defaults["global_def_win_y"] = y
  1662. self.defaults["global_def_win_w"] = width
  1663. self.defaults["global_def_win_h"] = height
  1664. self.defaults["def_notebook_width"] = notebook_width
  1665. self.save_defaults()
  1666. def message_dialog(self, title, message, kind="info"):
  1667. icon = {"info": QtWidgets.QMessageBox.Information,
  1668. "warning": QtWidgets.QMessageBox.Warning,
  1669. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1670. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1671. dlg.setText(message)
  1672. dlg.exec_()
  1673. def register_recent(self, kind, filename):
  1674. self.log.debug("register_recent()")
  1675. self.log.debug(" %s" % kind)
  1676. self.log.debug(" %s" % filename)
  1677. record = {'kind': str(kind), 'filename': str(filename)}
  1678. if record in self.recent:
  1679. return
  1680. self.recent.insert(0, record)
  1681. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1682. self.recent.pop()
  1683. try:
  1684. f = open(self.data_path + '/recent.json', 'w')
  1685. except IOError:
  1686. App.log.error("Failed to open recent items file for writing.")
  1687. self.inform.emit('[error_notcl]Failed to open recent files file for writing.')
  1688. return
  1689. #try:
  1690. json.dump(self.recent, f)
  1691. # except:
  1692. # App.log.error("Failed to write to recent items file.")
  1693. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1694. # f.close()
  1695. f.close()
  1696. # Re-buid the recent items menu
  1697. self.setup_recent_items()
  1698. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1699. """
  1700. Creates a new specalized FlatCAMObj and attaches it to the application,
  1701. this is, updates the GUI accordingly, any other records and plots it.
  1702. This method is thread-safe.
  1703. Notes:
  1704. * If the name is in use, the self.collection will modify it
  1705. when appending it to the collection. There is no need to handle
  1706. name conflicts here.
  1707. :param kind: The kind of object to create. One of 'gerber',
  1708. 'excellon', 'cncjob' and 'geometry'.
  1709. :type kind: str
  1710. :param name: Name for the object.
  1711. :type name: str
  1712. :param initialize: Function to run after creation of the object
  1713. but before it is attached to the application. The function is
  1714. called with 2 parameters: the new object and the App instance.
  1715. :type initialize: function
  1716. :return: None
  1717. :rtype: None
  1718. """
  1719. App.log.debug("new_object()")
  1720. self.plot = plot
  1721. self.autoselected = autoselected
  1722. t0 = time.time() # Debug
  1723. ## Create object
  1724. classdict = {
  1725. "gerber": FlatCAMGerber,
  1726. "excellon": FlatCAMExcellon,
  1727. "cncjob": FlatCAMCNCjob,
  1728. "geometry": FlatCAMGeometry
  1729. }
  1730. App.log.debug("Calling object constructor...")
  1731. obj = classdict[kind](name)
  1732. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1733. # Set options from "Project options" form
  1734. self.options_read_form()
  1735. # IMPORTANT
  1736. # The key names in defaults and options dictionary's are not random:
  1737. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1738. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1739. # the options from project options form into the self.options. After that, below, depending on the type of
  1740. # object that is created, it will strip the name of the object and the underline (if the original key was
  1741. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1742. # "toolchange"
  1743. for option in self.options:
  1744. if option.find(kind + "_") == 0:
  1745. oname = option[len(kind) + 1:]
  1746. obj.options[oname] = self.options[option]
  1747. # if kind == 'geometry':
  1748. # obj.tools = {}
  1749. # elif kind == 'cncjob':
  1750. # obj.cnc_tools = {}
  1751. # Initialize as per user request
  1752. # User must take care to implement initialize
  1753. # in a thread-safe way as is is likely that we
  1754. # have been invoked in a separate thread.
  1755. t1 = time.time()
  1756. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1757. try:
  1758. return_value = initialize(obj, self)
  1759. except Exception as e:
  1760. msg = "[error_notcl] An internal error has ocurred. See shell.\n"
  1761. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  1762. msg += traceback.format_exc()
  1763. self.inform.emit(msg)
  1764. # if str(e) == "Empty Geometry":
  1765. # self.inform.emit("[error_notcl] )
  1766. # else:
  1767. # self.inform.emit("[error] Object (%s) failed because: %s" % (kind, str(e)))
  1768. return "fail"
  1769. t2 = time.time()
  1770. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1771. if return_value == 'fail':
  1772. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1773. return "fail"
  1774. # Check units and convert if necessary
  1775. # This condition CAN be true because initialize() can change obj.units
  1776. if self.options["units"].upper() != obj.units.upper():
  1777. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1778. obj.convert_units(self.options["units"])
  1779. t3 = time.time()
  1780. self.log.debug("%f seconds converting units." % (t3 - t2))
  1781. # Create the bounding box for the object and then add the results to the obj.options
  1782. try:
  1783. xmin, ymin, xmax, ymax = obj.bounds()
  1784. obj.options['xmin'] = xmin
  1785. obj.options['ymin'] = ymin
  1786. obj.options['xmax'] = xmax
  1787. obj.options['ymax'] = ymax
  1788. except:
  1789. log.warning("The object has no bounds properties.")
  1790. pass
  1791. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1792. # Move the object to the main thread and let the app know that it is available.
  1793. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1794. self.object_created.emit(obj, self.plot, self.autoselected)
  1795. return obj
  1796. def new_excellon_object(self):
  1797. self.new_object('excellon', 'new_e', lambda x, y: None)
  1798. def on_object_created(self, obj, plot, autoselect):
  1799. """
  1800. Event callback for object creation.
  1801. :param obj: The newly created FlatCAM object.
  1802. :return: None
  1803. """
  1804. t0 = time.time() # DEBUG
  1805. self.log.debug("on_object_created()")
  1806. # The Collection might change the name if there is a collision
  1807. self.collection.append(obj)
  1808. # after adding the object to the collection always update the list of objects that are in the collection
  1809. self.all_objects_list = self.collection.get_list()
  1810. self.inform.emit("[success]Object (%s) created: %s" % (obj.kind, obj.options['name']))
  1811. self.new_object_available.emit(obj)
  1812. # update the SHELL auto-completer model with the name of the new object
  1813. self.myKeywords.append(obj.options['name'])
  1814. self.shell._edit.set_model_data(self.myKeywords)
  1815. if autoselect:
  1816. # select the just opened object but deselect the previous ones
  1817. self.collection.set_all_inactive()
  1818. self.collection.set_active(obj.options["name"])
  1819. def worker_task(obj):
  1820. with self.proc_container.new("Plotting"):
  1821. obj.plot()
  1822. t1 = time.time() # DEBUG
  1823. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1824. self.object_plotted.emit(obj)
  1825. # Send to worker
  1826. # self.worker.add_task(worker_task, [self])
  1827. if plot:
  1828. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1829. def on_object_changed(self, obj):
  1830. # update the bounding box data from obj.options
  1831. xmin, ymin, xmax, ymax = obj.bounds()
  1832. obj.options['xmin'] = xmin
  1833. obj.options['ymin'] = ymin
  1834. obj.options['xmax'] = xmax
  1835. obj.options['ymax'] = ymax
  1836. log.debug("Object changed, updating the bounding box data on self.options")
  1837. # delete the old selection shape
  1838. self.delete_selection_shape()
  1839. def on_object_plotted(self, obj):
  1840. self.on_zoom_fit(None)
  1841. def options_read_form(self):
  1842. for option in self.options_form_fields:
  1843. self.options[option] = self.options_form_fields[option].get_value()
  1844. def options_write_form(self):
  1845. for option in self.options:
  1846. self.options_write_form_field(option)
  1847. def options_write_form_field(self, field):
  1848. try:
  1849. self.options_form_fields[field].set_value(self.options[field])
  1850. except KeyError:
  1851. # Changed from error to debug. This allows to have data stored
  1852. # which is not user-editable.
  1853. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  1854. pass
  1855. def on_about(self):
  1856. """
  1857. Displays the "about" dialog.
  1858. :return: None
  1859. """
  1860. self.report_usage("on_about")
  1861. version = self.version
  1862. version_date = self.version_date
  1863. beta = self.beta
  1864. class AboutDialog(QtWidgets.QDialog):
  1865. def __init__(self, parent=None):
  1866. QtWidgets.QDialog.__init__(self, parent)
  1867. # Icon and title
  1868. self.setWindowIcon(parent.app_icon)
  1869. self.setWindowTitle("FlatCAM")
  1870. layout1 = QtWidgets.QVBoxLayout()
  1871. self.setLayout(layout1)
  1872. layout2 = QtWidgets.QHBoxLayout()
  1873. layout1.addLayout(layout2)
  1874. logo = QtWidgets.QLabel()
  1875. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  1876. layout2.addWidget(logo, stretch=0)
  1877. title = QtWidgets.QLabel(
  1878. "<font size=8><B>FlatCAM</B></font><BR>"
  1879. "Version %s %s (%s) - %s <BR>"
  1880. "<BR>"
  1881. "2D Computer-Aided Printed Circuit Board<BR>"
  1882. "Manufacturing.<BR>"
  1883. "<BR>"
  1884. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  1885. "<BR>"
  1886. "<B> Main Contributors:</B><BR>"
  1887. "Denis Hayrullin<BR>"
  1888. "Kamil Sopko<BR>"
  1889. "Marius Stanciu<BR>"
  1890. "Matthieu Berthomé<BR>"
  1891. "and many others found "
  1892. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  1893. "<BR>"
  1894. "Development is done "
  1895. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  1896. "DOWNLOAD area "
  1897. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  1898. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  1899. )
  1900. title.setOpenExternalLinks(True)
  1901. layout2.addWidget(title, stretch=1)
  1902. layout3 = QtWidgets.QHBoxLayout()
  1903. layout1.addLayout(layout3)
  1904. layout3.addStretch()
  1905. okbtn = QtWidgets.QPushButton("Close")
  1906. layout3.addWidget(okbtn)
  1907. okbtn.clicked.connect(self.accept)
  1908. AboutDialog(self.ui).exec_()
  1909. def on_file_savedefaults(self):
  1910. """
  1911. Callback for menu item File->Save Defaults. Saves application default options
  1912. ``self.defaults`` to current_defaults.FlatConfig.
  1913. :return: None
  1914. """
  1915. self.save_defaults()
  1916. def on_app_exit(self):
  1917. if self.collection.get_list():
  1918. msgbox = QtWidgets.QMessageBox()
  1919. # msgbox.setText("<B>Save changes ...</B>")
  1920. msgbox.setText("There are files/objects opened in FlatCAM. "
  1921. "\n"
  1922. "Do you want to Save the project?")
  1923. msgbox.setWindowTitle("Save changes")
  1924. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1925. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  1926. QtWidgets.QMessageBox.Cancel)
  1927. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  1928. response = msgbox.exec_()
  1929. if response == QtWidgets.QMessageBox.Yes:
  1930. self.on_file_saveprojectas(thread=False)
  1931. elif response == QtWidgets.QMessageBox.Cancel:
  1932. return
  1933. self.save_defaults()
  1934. else:
  1935. self.save_defaults()
  1936. log.debug("Application defaults saved ... Exit event.")
  1937. QtWidgets.qApp.quit()
  1938. def save_defaults(self, silent=False):
  1939. """
  1940. Saves application default options
  1941. ``self.defaults`` to current_defaults.FlatConfig.
  1942. :return: None
  1943. """
  1944. self.report_usage("save_defaults")
  1945. # Read options from file
  1946. try:
  1947. f = open(self.data_path + "/current_defaults.FlatConfig")
  1948. defaults_file_content = f.read()
  1949. f.close()
  1950. except:
  1951. e = sys.exc_info()[0]
  1952. App.log.error("Could not load defaults file.")
  1953. App.log.error(str(e))
  1954. self.inform.emit("[error_notcl] Could not load defaults file.")
  1955. return
  1956. try:
  1957. defaults = json.loads(defaults_file_content)
  1958. except:
  1959. e = sys.exc_info()[0]
  1960. App.log.error("Failed to parse defaults file.")
  1961. App.log.error(str(e))
  1962. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1963. return
  1964. # Update options
  1965. self.defaults_read_form()
  1966. defaults.update(self.defaults)
  1967. self.propagate_defaults(silent=True)
  1968. # Save update options
  1969. try:
  1970. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  1971. json.dump(defaults, f)
  1972. f.close()
  1973. except:
  1974. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1975. return
  1976. # Save the toolbar view
  1977. tb_status = 0
  1978. if self.ui.toolbarfile.isVisible():
  1979. tb_status += 1
  1980. if self.ui.toolbargeo.isVisible():
  1981. tb_status += 2
  1982. if self.ui.toolbarview.isVisible():
  1983. tb_status += 4
  1984. if self.ui.toolbartools.isVisible():
  1985. tb_status += 8
  1986. if self.ui.exc_edit_toolbar.isVisible():
  1987. tb_status += 16
  1988. if self.ui.geo_edit_toolbar.isVisible():
  1989. tb_status += 32
  1990. if self.ui.snap_toolbar.isVisible():
  1991. tb_status += 64
  1992. self.defaults["global_toolbar_view"] = tb_status
  1993. if not silent:
  1994. self.inform.emit("[success]Defaults saved.")
  1995. def save_factory_defaults(self, silent=False):
  1996. """
  1997. Saves application factory default options
  1998. ``self.defaults`` to factory_defaults.FlatConfig.
  1999. It's a one time job done just after the first install.
  2000. :return: None
  2001. """
  2002. self.report_usage("save_factory_defaults")
  2003. # Read options from file
  2004. try:
  2005. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2006. factory_defaults_file_content = f_f_def.read()
  2007. f_f_def.close()
  2008. except:
  2009. e = sys.exc_info()[0]
  2010. App.log.error("Could not load factory defaults file.")
  2011. App.log.error(str(e))
  2012. self.inform.emit("[error_notcl] Could not load factory defaults file.")
  2013. return
  2014. try:
  2015. factory_defaults = json.loads(factory_defaults_file_content)
  2016. except:
  2017. e = sys.exc_info()[0]
  2018. App.log.error("Failed to parse factory defaults file.")
  2019. App.log.error(str(e))
  2020. self.inform.emit("[error_notcl] Failed to parse factory defaults file.")
  2021. return
  2022. # Update options
  2023. self.defaults_read_form()
  2024. factory_defaults.update(self.defaults)
  2025. self.propagate_defaults(silent=True)
  2026. # Save update options
  2027. try:
  2028. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2029. json.dump(factory_defaults, f_f_def_s)
  2030. f_f_def_s.close()
  2031. except:
  2032. self.inform.emit("[error_notcl] Failed to write factory defaults to file.")
  2033. return
  2034. if silent is False:
  2035. self.inform.emit("Factory defaults saved.")
  2036. def final_save(self):
  2037. if self.collection.get_list():
  2038. msgbox = QtWidgets.QMessageBox()
  2039. # msgbox.setText("<B>Save changes ...</B>")
  2040. msgbox.setText("There are files/objects opened in FlatCAM. "
  2041. "\n"
  2042. "Do you want to Save the project?")
  2043. msgbox.setWindowTitle("Save changes")
  2044. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2045. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2046. QtWidgets.QMessageBox.Cancel)
  2047. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2048. response = msgbox.exec_()
  2049. if response == QtWidgets.QMessageBox.Yes:
  2050. self.on_file_saveprojectas(thread=False)
  2051. elif response == QtWidgets.QMessageBox.Cancel:
  2052. self.should_we_quit = False
  2053. return
  2054. self.save_defaults()
  2055. log.debug("Application defaults saved ... Exit event.")
  2056. def on_toggle_shell(self):
  2057. """
  2058. toggle shell if is visible close it if closed open it
  2059. :return:
  2060. """
  2061. if self.ui.shell_dock.isVisible():
  2062. self.ui.shell_dock.hide()
  2063. else:
  2064. self.ui.shell_dock.show()
  2065. def on_edit_join(self, name=None):
  2066. """
  2067. Callback for Edit->Join. Joins the selected geometry objects into
  2068. a new one.
  2069. :return: None
  2070. """
  2071. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2072. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2073. tooldias = []
  2074. geo_type_list = []
  2075. objs = self.collection.get_selected()
  2076. for obj in objs:
  2077. geo_type_list.append(obj.multigeo)
  2078. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2079. if len(set(geo_type_list)) != 1:
  2080. self.inform.emit("[error] Failed join. The Geometry objects are of different types.\n"
  2081. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2082. "convert from one to another and retry joining \n"
  2083. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2084. "the result may not be what was expected. \n"
  2085. "Check the generated GCODE.")
  2086. return
  2087. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2088. if True in geo_type_list:
  2089. def initialize(obj, app):
  2090. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2091. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2092. for v in obj.tools.values():
  2093. v['data']['name'] = obj_name_multi
  2094. self.new_object("geometry", obj_name_multi, initialize)
  2095. else:
  2096. def initialize(obj, app):
  2097. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2098. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2099. for v in obj.tools.values():
  2100. v['data']['name'] = obj_name_single
  2101. self.new_object("geometry", obj_name_single, initialize)
  2102. def on_edit_join_exc(self):
  2103. """
  2104. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2105. a new one.
  2106. :return: None
  2107. """
  2108. objs = self.collection.get_selected()
  2109. for obj in objs:
  2110. if not isinstance(obj, FlatCAMExcellon):
  2111. self.inform.emit("[error_notcl]Failed. Excellon joining works only on Excellon objects.")
  2112. return
  2113. def initialize(obj, app):
  2114. FlatCAMExcellon.merge(objs, obj)
  2115. self.new_object("excellon", 'Combo_Excellon', initialize)
  2116. def on_edit_join_grb(self):
  2117. """
  2118. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2119. a new one.
  2120. :return: None
  2121. """
  2122. objs = self.collection.get_selected()
  2123. for obj in objs:
  2124. if not isinstance(obj, FlatCAMGerber):
  2125. self.inform.emit("[error_notcl]Failed. Gerber joining works only on Gerber objects.")
  2126. return
  2127. def initialize(obj, app):
  2128. FlatCAMGerber.merge(objs, obj)
  2129. self.new_object("gerber", 'Combo_Gerber', initialize)
  2130. def on_convert_singlegeo_to_multigeo(self):
  2131. obj = self.collection.get_active()
  2132. if obj is None:
  2133. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  2134. return
  2135. if not isinstance(obj, FlatCAMGeometry):
  2136. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  2137. return
  2138. obj.multigeo = True
  2139. for tooluid, dict_value in obj.tools.items():
  2140. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2141. if not isinstance(obj.solid_geometry, list):
  2142. obj.solid_geometry = [obj.solid_geometry]
  2143. obj.solid_geometry[:] = []
  2144. obj.plot()
  2145. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2146. def on_convert_multigeo_to_singlegeo(self):
  2147. obj = self.collection.get_active()
  2148. if obj is None:
  2149. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  2150. return
  2151. if not isinstance(obj, FlatCAMGeometry):
  2152. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  2153. return
  2154. obj.multigeo = False
  2155. total_solid_geometry = []
  2156. for tooluid, dict_value in obj.tools.items():
  2157. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2158. # clear the original geometry
  2159. dict_value['solid_geometry'][:] = []
  2160. obj.solid_geometry = deepcopy(total_solid_geometry)
  2161. obj.plot()
  2162. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2163. def on_options_dict_change(self, field):
  2164. self.options_write_form_field(field)
  2165. if field == "units":
  2166. self.set_screen_units(self.options['units'])
  2167. def on_defaults_dict_change(self, field):
  2168. self.defaults_write_form_field(field)
  2169. def set_screen_units(self, units):
  2170. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2171. def on_toggle_units(self):
  2172. """
  2173. Callback for the Units radio-button change in the Options tab.
  2174. Changes the application's default units or the current project's units.
  2175. If changing the project's units, the change propagates to all of
  2176. the objects in the project.
  2177. :return: None
  2178. """
  2179. self.report_usage("on_toggle_units")
  2180. if self.toggle_units_ignore:
  2181. return
  2182. # If option is the same, then ignore
  2183. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2184. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2185. return
  2186. # Options to scale
  2187. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2188. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2189. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2190. 'gerber_noncoppermargin','gerber_bboxmargin',
  2191. 'excellon_drillz', "excellon_toolchangexy",
  2192. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2193. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2194. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2195. 'geometry_cnctooldia', 'tools_painttooldia', 'tools_paintoverlap', 'geometry_toolchangexy',
  2196. 'geometry_toolchangez',
  2197. 'tools_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2198. def scale_options(sfactor):
  2199. for dim in dimensions:
  2200. if dim == 'excellon_toolchangexy':
  2201. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2202. coords_xy[0] *= sfactor
  2203. coords_xy[1] *= sfactor
  2204. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2205. elif dim == 'geometry_toolchangexy':
  2206. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2207. coords_xy[0] *= sfactor
  2208. coords_xy[1] *= sfactor
  2209. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2210. else:
  2211. self.options[dim] *= sfactor
  2212. # The scaling factor depending on choice of units.
  2213. factor = 1/25.4
  2214. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2215. factor = 25.4
  2216. # Changing project units. Warn user.
  2217. msgbox = QtWidgets.QMessageBox()
  2218. msgbox.setText("<B>Change project units ...</B>")
  2219. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2220. "properties of all objects to be scaled accordingly. Continue?")
  2221. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2222. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2223. response = msgbox.exec_()
  2224. if response == QtWidgets.QMessageBox.Ok:
  2225. self.options_read_form()
  2226. scale_options(factor)
  2227. self.options_write_form()
  2228. # change this only if the workspace is active
  2229. if self.defaults['global_workspace'] is True:
  2230. self.plotcanvas.draw_workspace()
  2231. # adjust the grid values on the main toolbar
  2232. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2233. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2234. for obj in self.collection.get_list():
  2235. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2236. obj.convert_units(units)
  2237. # make that the properties stored in the object are also updated
  2238. self.object_changed.emit(obj)
  2239. obj.build_ui()
  2240. current = self.collection.get_active()
  2241. if current is not None:
  2242. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2243. if not isinstance(current, FlatCAMGeometry):
  2244. current.to_form()
  2245. self.plot_all()
  2246. else:
  2247. # Undo toggling
  2248. self.toggle_units_ignore = True
  2249. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2250. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2251. else:
  2252. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2253. self.toggle_units_ignore = False
  2254. self.options_read_form()
  2255. self.inform.emit("Converted units to %s" % self.options["units"])
  2256. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  2257. self.set_screen_units(self.options["units"])
  2258. def on_toggle_units_click(self):
  2259. if self.options["units"] == 'MM':
  2260. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2261. else:
  2262. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2263. self.on_toggle_units()
  2264. def on_language_apply(self):
  2265. # TODO: apply the language
  2266. # app restart section
  2267. pass
  2268. def on_fullscreen(self):
  2269. if self.toggle_fscreen is False:
  2270. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2271. tb.setVisible(False)
  2272. self.ui.splitter_left.setVisible(False)
  2273. self.toggle_fscreen = True
  2274. else:
  2275. self.restore_toolbar_view()
  2276. self.ui.splitter_left.setVisible(True)
  2277. self.toggle_fscreen = False
  2278. def on_toggle_plotarea(self):
  2279. try:
  2280. name = self.ui.plot_tab_area.widget(0).objectName()
  2281. except AttributeError:
  2282. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2283. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2284. self.ui.plot_tab_area.protectTab(0)
  2285. return
  2286. if name != 'plotarea':
  2287. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2288. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2289. self.ui.plot_tab_area.protectTab(0)
  2290. else:
  2291. self.ui.plot_tab_area.closeTab(0)
  2292. def on_toggle_axis(self):
  2293. if self.toggle_axis is False:
  2294. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2295. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2296. self.plotcanvas.redraw()
  2297. self.toggle_axis = True
  2298. else:
  2299. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2300. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2301. self.plotcanvas.redraw()
  2302. self.toggle_axis = False
  2303. def on_toggle_grid(self):
  2304. self.ui.grid_snap_btn.trigger()
  2305. def on_options_combo_change(self, sel):
  2306. """
  2307. Called when the combo box to choose between application defaults and
  2308. project option changes value. The corresponding variables are
  2309. copied to the UI.
  2310. :param sel: The option index that was chosen.
  2311. :return: None
  2312. """
  2313. # combo_sel = self.ui.notebook.combo_options.get_active()
  2314. App.log.debug("Options --> %s" % sel)
  2315. # form = [self.defaults_form, self.options_form][sel]
  2316. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2317. if sel == 0:
  2318. self.gen_form = self.general_defaults_form
  2319. self.ger_form = self.gerber_defaults_form
  2320. self.exc_form = self.excellon_defaults_form
  2321. self.geo_form = self.geometry_defaults_form
  2322. self.cnc_form = self.cncjob_defaults_form
  2323. self.tools_form = self.tools_defaults_form
  2324. elif sel == 1:
  2325. self.gen_form = self.general_options_form
  2326. self.ger_form = self.gerber_options_form
  2327. self.exc_form = self.excellon_options_form
  2328. self.geo_form = self.geometry_options_form
  2329. self.cnc_form = self.cncjob_options_form
  2330. self.tools_form = self.tools_options_form
  2331. else:
  2332. return
  2333. try:
  2334. self.ui.general_scroll_area.takeWidget()
  2335. except:
  2336. self.log.debug("Nothing to remove")
  2337. self.ui.general_scroll_area.setWidget(self.gen_form)
  2338. self.gen_form.show()
  2339. try:
  2340. self.ui.gerber_scroll_area.takeWidget()
  2341. except:
  2342. self.log.debug("Nothing to remove")
  2343. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2344. self.ger_form.show()
  2345. try:
  2346. self.ui.excellon_scroll_area.takeWidget()
  2347. except:
  2348. self.log.debug("Nothing to remove")
  2349. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2350. self.exc_form.show()
  2351. try:
  2352. self.ui.geometry_scroll_area.takeWidget()
  2353. except:
  2354. self.log.debug("Nothing to remove")
  2355. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2356. self.geo_form.show()
  2357. try:
  2358. self.ui.cncjob_scroll_area.takeWidget()
  2359. except:
  2360. self.log.debug("Nothing to remove")
  2361. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2362. self.cnc_form.show()
  2363. try:
  2364. self.ui.tools_scroll_area.takeWidget()
  2365. except:
  2366. self.log.debug("Nothing to remove")
  2367. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2368. self.tools_form.show()
  2369. self.log.debug("Finished GUI form initialization.")
  2370. # self.options2form()
  2371. def on_excellon_defaults_button(self):
  2372. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2373. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2374. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2375. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2376. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2377. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2378. log.debug("Excellon app defaults loaded ...")
  2379. def on_excellon_options_button(self):
  2380. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2381. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2382. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2383. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2384. self.options_form_fields["excellon_zeros"].set_value('L')
  2385. self.options_form_fields["excellon_units"].set_value('INCH')
  2386. log.debug("Excellon options defaults loaded ...")
  2387. # Setting plot colors handlers
  2388. def on_pf_color_entry(self):
  2389. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2390. self.defaults['global_plot_fill'][7:9]
  2391. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2392. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2393. def on_pf_color_button(self):
  2394. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2395. c_dialog = QtWidgets.QColorDialog()
  2396. plot_fill_color = c_dialog.getColor(initial=current_color)
  2397. if plot_fill_color.isValid() is False:
  2398. return
  2399. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2400. "background-color:%s" % str(plot_fill_color.name()))
  2401. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2402. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2403. self.defaults['global_plot_fill'] = new_val
  2404. def on_pf_color_spinner(self):
  2405. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2406. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2407. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2408. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2409. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2410. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2411. def on_pf_color_slider(self):
  2412. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2413. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2414. def on_pl_color_entry(self):
  2415. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2416. self.defaults['global_plot_line'][7:9]
  2417. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2418. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2419. def on_pl_color_button(self):
  2420. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2421. # print(current_color)
  2422. c_dialog = QtWidgets.QColorDialog()
  2423. plot_line_color = c_dialog.getColor(initial=current_color)
  2424. if plot_line_color.isValid() is False:
  2425. return
  2426. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2427. "background-color:%s" % str(plot_line_color.name()))
  2428. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2429. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2430. self.defaults['global_plot_line'] = new_val_line
  2431. # Setting selection colors (left - right) handlers
  2432. def on_sf_color_entry(self):
  2433. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2434. self.defaults['global_sel_fill'][7:9]
  2435. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2436. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2437. def on_sf_color_button(self):
  2438. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2439. c_dialog = QtWidgets.QColorDialog()
  2440. plot_fill_color = c_dialog.getColor(initial=current_color)
  2441. if plot_fill_color.isValid() is False:
  2442. return
  2443. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2444. "background-color:%s" % str(plot_fill_color.name()))
  2445. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2446. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2447. self.defaults['global_sel_fill'] = new_val
  2448. def on_sf_color_spinner(self):
  2449. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2450. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2451. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2452. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2453. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2454. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2455. def on_sf_color_slider(self):
  2456. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2457. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2458. def on_sl_color_entry(self):
  2459. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2460. self.defaults['global_sel_line'][7:9]
  2461. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2462. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2463. def on_sl_color_button(self):
  2464. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2465. c_dialog = QtWidgets.QColorDialog()
  2466. plot_line_color = c_dialog.getColor(initial=current_color)
  2467. if plot_line_color.isValid() is False:
  2468. return
  2469. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2470. "background-color:%s" % str(plot_line_color.name()))
  2471. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2472. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2473. self.defaults['global_sel_line'] = new_val_line
  2474. # Setting selection colors (right - left) handlers
  2475. def on_alt_sf_color_entry(self):
  2476. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2477. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2478. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2479. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2480. def on_alt_sf_color_button(self):
  2481. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2482. c_dialog = QtWidgets.QColorDialog()
  2483. plot_fill_color = c_dialog.getColor(initial=current_color)
  2484. if plot_fill_color.isValid() is False:
  2485. return
  2486. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2487. "background-color:%s" % str(plot_fill_color.name()))
  2488. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2489. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2490. self.defaults['global_alt_sel_fill'] = new_val
  2491. def on_alt_sf_color_spinner(self):
  2492. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2493. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2494. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2495. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2496. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2497. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2498. def on_alt_sf_color_slider(self):
  2499. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2500. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2501. def on_alt_sl_color_entry(self):
  2502. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2503. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2504. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2505. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2506. def on_alt_sl_color_button(self):
  2507. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2508. c_dialog = QtWidgets.QColorDialog()
  2509. plot_line_color = c_dialog.getColor(initial=current_color)
  2510. if plot_line_color.isValid() is False:
  2511. return
  2512. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2513. "background-color:%s" % str(plot_line_color.name()))
  2514. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2515. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2516. self.defaults['global_alt_sel_line'] = new_val_line
  2517. # Setting Editor colors
  2518. def on_draw_color_entry(self):
  2519. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2520. .draw_color_entry.get_value()
  2521. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2522. "background-color:%s" % str(self.defaults['global_draw_color']))
  2523. def on_draw_color_button(self):
  2524. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2525. c_dialog = QtWidgets.QColorDialog()
  2526. draw_color = c_dialog.getColor(initial=current_color)
  2527. if draw_color.isValid() is False:
  2528. return
  2529. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2530. "background-color:%s" % str(draw_color.name()))
  2531. new_val = str(draw_color.name())
  2532. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2533. self.defaults['global_draw_color'] = new_val
  2534. def on_sel_draw_color_entry(self):
  2535. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2536. .sel_draw_color_entry.get_value()
  2537. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2538. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2539. def on_sel_draw_color_button(self):
  2540. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2541. c_dialog = QtWidgets.QColorDialog()
  2542. sel_draw_color = c_dialog.getColor(initial=current_color)
  2543. if sel_draw_color.isValid() is False:
  2544. return
  2545. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2546. "background-color:%s" % str(sel_draw_color.name()))
  2547. new_val_sel = str(sel_draw_color.name())
  2548. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2549. self.defaults['global_sel_draw_color'] = new_val_sel
  2550. def on_workspace_modified(self):
  2551. self.save_defaults(silent=True)
  2552. self.plotcanvas.draw_workspace()
  2553. def on_workspace(self):
  2554. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2555. self.plotcanvas.restore_workspace()
  2556. else:
  2557. self.plotcanvas.delete_workspace()
  2558. self.save_defaults(silent=True)
  2559. def on_workspace_menu(self):
  2560. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2561. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2562. else:
  2563. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2564. self.on_workspace()
  2565. def on_theme(self):
  2566. current_theme= self.general_defaults_form.general_gui_group.theme_combo.get_value().lower()
  2567. settings = QSettings("Open Source", "FlatCAM")
  2568. settings.setValue('theme', current_theme)
  2569. # This will write the setting to the platform specific storage.
  2570. del settings
  2571. # first remove the toolbars:
  2572. self.ui.removeToolBar(self.ui.toolbarfile)
  2573. self.ui.removeToolBar(self.ui.toolbargeo)
  2574. self.ui.removeToolBar(self.ui.toolbarview)
  2575. self.ui.removeToolBar(self.ui.toolbartools)
  2576. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  2577. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  2578. self.ui.removeToolBar(self.ui.snap_toolbar)
  2579. if current_theme == 'standard':
  2580. ### TOOLBAR INSTALLATION ###
  2581. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2582. self.ui.toolbarfile.setObjectName('File_TB')
  2583. self.ui.addToolBar(self.ui.toolbarfile)
  2584. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2585. self.ui.toolbargeo.setObjectName('Edit_TB')
  2586. self.ui.addToolBar(self.ui.toolbargeo)
  2587. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2588. self.ui.toolbarview.setObjectName('View_TB')
  2589. self.ui.addToolBar(self.ui.toolbarview)
  2590. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2591. self.ui.toolbartools.setObjectName('Tools_TB')
  2592. self.ui.addToolBar(self.ui.toolbartools)
  2593. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2594. self.ui.exc_edit_toolbar.setVisible(False)
  2595. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2596. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  2597. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2598. self.ui.geo_edit_toolbar.setVisible(False)
  2599. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2600. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  2601. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2602. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2603. # self.ui.snap_toolbar.setMaximumHeight(30)
  2604. self.ui.addToolBar(self.ui.snap_toolbar)
  2605. self.ui.corner_snap_btn.setVisible(False)
  2606. self.ui.snap_magnet.setVisible(False)
  2607. elif current_theme == 'compact':
  2608. ### TOOLBAR INSTALLATION ###
  2609. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2610. self.ui.toolbarfile.setObjectName('File_TB')
  2611. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  2612. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2613. self.ui.toolbargeo.setObjectName('Edit_TB')
  2614. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  2615. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2616. self.ui.toolbarview.setObjectName('View_TB')
  2617. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  2618. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2619. self.ui.toolbartools.setObjectName('Tools_TB')
  2620. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  2621. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2622. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2623. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.exc_edit_toolbar)
  2624. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2625. self.ui.geo_edit_toolbar.setVisible(False)
  2626. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2627. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  2628. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2629. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2630. self.ui.snap_toolbar.setMaximumHeight(30)
  2631. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  2632. self.ui.corner_snap_btn.setVisible(True)
  2633. self.ui.snap_magnet.setVisible(True)
  2634. self.ui.populate_toolbars()
  2635. self.ui.grid_snap_btn.setChecked(True)
  2636. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  2637. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  2638. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  2639. self.ui.grid_gap_link_cb.setChecked(True)
  2640. def on_save_button(self):
  2641. self.save_defaults(silent=False)
  2642. # load the defaults so they are updated into the app
  2643. self.load_defaults(filename='current_defaults')
  2644. # Re-fresh project options
  2645. self.on_options_app2project()
  2646. def handleOpen(self):
  2647. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2648. "All Files (*.*)"
  2649. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2650. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2651. if path:
  2652. file = QtCore.QFile(path)
  2653. if file.open(QtCore.QIODevice.ReadOnly):
  2654. stream = QtCore.QTextStream(file)
  2655. self.gcode_edited = stream.readAll()
  2656. self.ui.code_editor.setPlainText(self.gcode_edited)
  2657. file.close()
  2658. def handlePrint(self):
  2659. dialog = QtPrintSupport.QPrintDialog()
  2660. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2661. self.ui.code_editor.document().print_(dialog.printer())
  2662. def handlePreview(self):
  2663. dialog = QtPrintSupport.QPrintPreviewDialog()
  2664. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2665. dialog.exec_()
  2666. def handleTextChanged(self):
  2667. # enable = not self.ui.code_editor.document().isEmpty()
  2668. # self.ui.buttonPrint.setEnabled(enable)
  2669. # self.ui.buttonPreview.setEnabled(enable)
  2670. pass
  2671. def handleSaveGCode(self):
  2672. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2673. "All Files (*.*)"
  2674. try:
  2675. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2676. caption="Export G-Code ...", directory=self.defaults["global_last_folder"], filter=_filter_)[0])
  2677. except TypeError:
  2678. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2679. try:
  2680. my_gcode = self.ui.code_editor.toPlainText()
  2681. with open(filename, 'w') as f:
  2682. for line in my_gcode:
  2683. f.write(line)
  2684. except FileNotFoundError:
  2685. self.inform.emit("[WARNING] No such file or directory")
  2686. return
  2687. # Just for adding it to the recent files list.
  2688. self.file_opened.emit("cncjob", filename)
  2689. self.file_saved.emit("cncjob", filename)
  2690. self.inform.emit("Saved to: " + filename)
  2691. def handleFindGCode(self):
  2692. flags = QtGui.QTextDocument.FindCaseSensitively
  2693. text_to_be_found = self.ui.entryFind.get_value()
  2694. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2695. if r is False:
  2696. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2697. def handleReplaceGCode(self):
  2698. old = self.ui.entryFind.get_value()
  2699. new = self.ui.entryReplace.get_value()
  2700. if self.ui.sel_all_cb.isChecked():
  2701. while True:
  2702. cursor = self.ui.code_editor.textCursor()
  2703. cursor.beginEditBlock()
  2704. flags = QtGui.QTextDocument.FindCaseSensitively
  2705. # self.ui.editor is the QPlainTextEdit
  2706. r = self.ui.code_editor.find(str(old), flags)
  2707. if r:
  2708. qc = self.ui.code_editor.textCursor()
  2709. if qc.hasSelection():
  2710. qc.insertText(new)
  2711. else:
  2712. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2713. break
  2714. # Mark end of undo block
  2715. cursor.endEditBlock()
  2716. else:
  2717. cursor = self.ui.code_editor.textCursor()
  2718. cursor.beginEditBlock()
  2719. qc = self.ui.code_editor.textCursor()
  2720. if qc.hasSelection():
  2721. qc.insertText(new)
  2722. # Mark end of undo block
  2723. cursor.endEditBlock()
  2724. def on_new_geometry(self):
  2725. def initialize(obj, self):
  2726. obj.multitool = False
  2727. self.new_object('geometry', 'new_g', initialize)
  2728. self.plot_all()
  2729. def on_delete(self):
  2730. """
  2731. Delete the currently selected FlatCAMObjs.
  2732. :return: None
  2733. """
  2734. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  2735. # a geometry object before we update it.
  2736. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  2737. if self.collection.get_active():
  2738. self.log.debug("on_delete()")
  2739. self.report_usage("on_delete")
  2740. while (self.collection.get_active()):
  2741. self.delete_first_selected()
  2742. self.inform.emit("Object(s) deleted ...")
  2743. # make sure that the selection shape is deleted, too
  2744. self.delete_selection_shape()
  2745. else:
  2746. self.inform.emit("Failed. No object(s) selected...")
  2747. else:
  2748. self.inform.emit("Save the work in Editor and try again ...")
  2749. def on_set_origin(self):
  2750. """
  2751. Set the origin to the left mouse click position
  2752. :return: None
  2753. """
  2754. #display the message for the user
  2755. #and ask him to click on the desired position
  2756. self.inform.emit('Click to set the origin ...')
  2757. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  2758. def on_jump_to(self):
  2759. """
  2760. Jump to a location by setting the mouse cursor location
  2761. :return:
  2762. """
  2763. dia_box = Dialog_box(title="Jump to Coordinates", label="Enter the coordinates in format X,Y:")
  2764. if dia_box.ok is True:
  2765. try:
  2766. location = eval(dia_box.location)
  2767. if not isinstance(location, tuple):
  2768. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  2769. return
  2770. except:
  2771. return
  2772. else:
  2773. return
  2774. self.plotcanvas.fit_center(loc=location)
  2775. cursor = QtGui.QCursor()
  2776. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  2777. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  2778. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  2779. self.inform.emit("Done.")
  2780. def on_copy_object(self):
  2781. def initialize(obj_init, app):
  2782. obj_init.solid_geometry = obj.solid_geometry
  2783. try:
  2784. if obj.tools:
  2785. obj_init.tools = obj.tools
  2786. except Exception as e:
  2787. log.debug("on_copy_object() --> %s" % str(e))
  2788. def initialize_excellon(obj_init, app):
  2789. obj_init.tools = obj.tools
  2790. # drills are offset, so they need to be deep copied
  2791. obj_init.drills = deepcopy(obj.drills)
  2792. # slots are offset, so they need to be deep copied
  2793. obj_init.slots = deepcopy(obj.slots)
  2794. obj_init.create_geometry()
  2795. for obj in self.collection.get_selected():
  2796. obj_name = obj.options["name"]
  2797. try:
  2798. if isinstance(obj, FlatCAMExcellon):
  2799. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  2800. elif isinstance(obj,FlatCAMGerber):
  2801. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  2802. elif isinstance(obj,FlatCAMGeometry):
  2803. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  2804. except Exception as e:
  2805. return "Operation failed: %s" % str(e)
  2806. def on_copy_object2(self, custom_name):
  2807. def initialize_geometry(obj_init, app):
  2808. obj_init.solid_geometry = obj.solid_geometry
  2809. try:
  2810. if obj.tools:
  2811. obj_init.tools = obj.tools
  2812. except Exception as e:
  2813. log.debug("on_copy_object2() --> %s" % str(e))
  2814. def initialize_gerber(obj_init, app):
  2815. obj_init.solid_geometry = obj.solid_geometry
  2816. obj_init.apertures = deepcopy(obj.apertures)
  2817. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  2818. def initialize_excellon(obj_init, app):
  2819. obj_init.tools = obj.tools
  2820. # drills are offset, so they need to be deep copied
  2821. obj_init.drills = deepcopy(obj.drills)
  2822. # slots are offset, so they need to be deep copied
  2823. obj_init.slots = deepcopy(obj.slots)
  2824. obj_init.create_geometry()
  2825. for obj in self.collection.get_selected():
  2826. obj_name = obj.options["name"]
  2827. try:
  2828. if isinstance(obj, FlatCAMExcellon):
  2829. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  2830. elif isinstance(obj,FlatCAMGerber):
  2831. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  2832. elif isinstance(obj,FlatCAMGeometry):
  2833. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  2834. except Exception as e:
  2835. return "Operation failed: %s" % str(e)
  2836. def on_rename_object(self, text):
  2837. named_obj = self.collection.get_active()
  2838. for obj in named_obj:
  2839. if obj is list:
  2840. self.on_rename_object(text)
  2841. else:
  2842. try:
  2843. obj.options['name'] = text
  2844. except:
  2845. log.warning("Could not rename the object in the list")
  2846. def on_copy_object_as_geometry(self):
  2847. def initialize(obj_init, app):
  2848. obj_init.solid_geometry = obj.solid_geometry
  2849. if obj.tools:
  2850. obj_init.tools = obj.tools
  2851. def initialize_excellon(obj, app):
  2852. objs = self.collection.get_selected()
  2853. FlatCAMGeometry.merge(objs, obj)
  2854. for obj in self.collection.get_selected():
  2855. obj_name = obj.options["name"]
  2856. try:
  2857. if isinstance(obj, FlatCAMExcellon):
  2858. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  2859. else:
  2860. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  2861. except Exception as e:
  2862. return "Operation failed: %s" % str(e)
  2863. def on_set_zero_click(self, event):
  2864. #this function will be available only for mouse left click
  2865. pos =[]
  2866. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  2867. if event.button == 1:
  2868. if self.grid_status() == True:
  2869. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2870. else:
  2871. pos = pos_canvas
  2872. x = 0 - pos[0]
  2873. y = 0 - pos[1]
  2874. for obj in self.collection.get_list():
  2875. obj.offset((x,y))
  2876. self.object_changed.emit(obj)
  2877. # obj.plot()
  2878. self.plot_all()
  2879. self.inform.emit('[success] Origin set ...')
  2880. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  2881. def on_selectall(self):
  2882. # delete the possible selection box around a possible selected object
  2883. self.delete_selection_shape()
  2884. for name in self.collection.get_names():
  2885. self.collection.set_active(name)
  2886. curr_sel_obj = self.collection.get_by_name(name)
  2887. # create the selection box around the selected object
  2888. self.draw_selection_shape(curr_sel_obj)
  2889. def on_preferences(self):
  2890. # add the tab if it was closed
  2891. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  2892. # delete the absolute and relative position and messages in the infobar
  2893. self.ui.position_label.setText("")
  2894. self.ui.rel_position_label.setText("")
  2895. # Switch plot_area to preferences page
  2896. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  2897. self.ui.show()
  2898. def on_flipy(self):
  2899. obj_list = self.collection.get_selected()
  2900. xminlist = []
  2901. yminlist = []
  2902. xmaxlist = []
  2903. ymaxlist = []
  2904. if not obj_list:
  2905. self.inform.emit("[warning_notcl] No object selected to Flip on Y axis.")
  2906. else:
  2907. try:
  2908. # first get a bounding box to fit all
  2909. for obj in obj_list:
  2910. xmin, ymin, xmax, ymax = obj.bounds()
  2911. xminlist.append(xmin)
  2912. yminlist.append(ymin)
  2913. xmaxlist.append(xmax)
  2914. ymaxlist.append(ymax)
  2915. # get the minimum x,y and maximum x,y for all objects selected
  2916. xminimal = min(xminlist)
  2917. yminimal = min(yminlist)
  2918. xmaximal = max(xmaxlist)
  2919. ymaximal = max(ymaxlist)
  2920. px = 0.5 * (xminimal + xmaximal)
  2921. py = 0.5 * (yminimal + ymaximal)
  2922. # execute mirroring
  2923. for obj in obj_list:
  2924. obj.mirror('X', [px, py])
  2925. obj.plot()
  2926. self.object_changed.emit(obj)
  2927. except Exception as e:
  2928. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2929. return
  2930. def on_flipx(self):
  2931. obj_list = self.collection.get_selected()
  2932. xminlist = []
  2933. yminlist = []
  2934. xmaxlist = []
  2935. ymaxlist = []
  2936. if not obj_list:
  2937. self.inform.emit("[warning_notcl] No object selected to Flip on X axis.")
  2938. else:
  2939. try:
  2940. # first get a bounding box to fit all
  2941. for obj in obj_list:
  2942. xmin, ymin, xmax, ymax = obj.bounds()
  2943. xminlist.append(xmin)
  2944. yminlist.append(ymin)
  2945. xmaxlist.append(xmax)
  2946. ymaxlist.append(ymax)
  2947. # get the minimum x,y and maximum x,y for all objects selected
  2948. xminimal = min(xminlist)
  2949. yminimal = min(yminlist)
  2950. xmaximal = max(xmaxlist)
  2951. ymaximal = max(ymaxlist)
  2952. px = 0.5 * (xminimal + xmaximal)
  2953. py = 0.5 * (yminimal + ymaximal)
  2954. # execute mirroring
  2955. for obj in obj_list:
  2956. obj.mirror('Y', [px, py])
  2957. obj.plot()
  2958. self.object_changed.emit(obj)
  2959. except Exception as e:
  2960. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2961. return
  2962. def on_rotate(self, silent=False, preset=None):
  2963. obj_list = self.collection.get_selected()
  2964. xminlist = []
  2965. yminlist = []
  2966. xmaxlist = []
  2967. ymaxlist = []
  2968. if not obj_list:
  2969. self.inform.emit("[warning_notcl] No object selected to Rotate.")
  2970. else:
  2971. if silent is False:
  2972. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2973. min=-360, max=360, decimals=3)
  2974. num, ok = rotatebox.get_value()
  2975. else:
  2976. num = preset
  2977. ok = True
  2978. if ok:
  2979. try:
  2980. # first get a bounding box to fit all
  2981. for obj in obj_list:
  2982. xmin, ymin, xmax, ymax = obj.bounds()
  2983. xminlist.append(xmin)
  2984. yminlist.append(ymin)
  2985. xmaxlist.append(xmax)
  2986. ymaxlist.append(ymax)
  2987. # get the minimum x,y and maximum x,y for all objects selected
  2988. xminimal = min(xminlist)
  2989. yminimal = min(yminlist)
  2990. xmaximal = max(xmaxlist)
  2991. ymaximal = max(ymaxlist)
  2992. px = 0.5 * (xminimal + xmaximal)
  2993. py = 0.5 * (yminimal + ymaximal)
  2994. for sel_obj in obj_list:
  2995. sel_obj.rotate(-num, point=(px, py))
  2996. sel_obj.plot()
  2997. self.object_changed.emit(sel_obj)
  2998. except Exception as e:
  2999. self.inform.emit("[error_notcl] Due of %s, rotation movement was not executed." % str(e))
  3000. return
  3001. def on_skewx(self):
  3002. obj_list = self.collection.get_selected()
  3003. xminlist = []
  3004. yminlist = []
  3005. if not obj_list:
  3006. self.inform.emit("[warning_notcl] No object selected to Skew/Shear on X axis.")
  3007. else:
  3008. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3009. min=-360, max=360, decimals=3)
  3010. num, ok = skewxbox.get_value()
  3011. if ok:
  3012. # first get a bounding box to fit all
  3013. for obj in obj_list:
  3014. xmin, ymin, xmax, ymax = obj.bounds()
  3015. xminlist.append(xmin)
  3016. yminlist.append(ymin)
  3017. # get the minimum x,y and maximum x,y for all objects selected
  3018. xminimal = min(xminlist)
  3019. yminimal = min(yminlist)
  3020. for obj in obj_list:
  3021. obj.skew(num, 0, point=(xminimal, yminimal))
  3022. obj.plot()
  3023. self.object_changed.emit(obj)
  3024. def on_skewy(self):
  3025. obj_list = self.collection.get_selected()
  3026. xminlist = []
  3027. yminlist = []
  3028. if not obj_list:
  3029. self.inform.emit("[warning_notcl] No object selected to Skew/Shear on Y axis.")
  3030. else:
  3031. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3032. min=-360, max=360, decimals=3)
  3033. num, ok = skewybox.get_value()
  3034. if ok:
  3035. # first get a bounding box to fit all
  3036. for obj in obj_list:
  3037. xmin, ymin, xmax, ymax = obj.bounds()
  3038. xminlist.append(xmin)
  3039. yminlist.append(ymin)
  3040. # get the minimum x,y and maximum x,y for all objects selected
  3041. xminimal = min(xminlist)
  3042. yminimal = min(yminlist)
  3043. for obj in obj_list:
  3044. obj.skew(0, num, point=(xminimal, yminimal))
  3045. obj.plot()
  3046. self.object_changed.emit(obj)
  3047. def delete_first_selected(self):
  3048. # Keep this for later
  3049. try:
  3050. name = self.collection.get_active().options["name"]
  3051. except AttributeError:
  3052. self.log.debug("Nothing selected for deletion")
  3053. return
  3054. # Remove plot
  3055. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3056. # self.plotcanvas.auto_adjust_axes()
  3057. # Clear form
  3058. self.setup_component_editor()
  3059. # Remove from dictionary
  3060. self.collection.delete_active()
  3061. self.inform.emit("Object deleted: %s" % name)
  3062. def on_plots_updated(self):
  3063. """
  3064. Callback used to report when the plots have changed.
  3065. Adjust axes and zooms to fit.
  3066. :return: None
  3067. """
  3068. # self.plotcanvas.auto_adjust_axes()
  3069. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3070. self.on_zoom_fit(None)
  3071. # TODO: Rework toolbar 'clear', 'replot' functions
  3072. def on_toolbar_replot(self):
  3073. """
  3074. Callback for toolbar button. Re-plots all objects.
  3075. :return: None
  3076. """
  3077. self.report_usage("on_toolbar_replot")
  3078. self.log.debug("on_toolbar_replot()")
  3079. try:
  3080. self.collection.get_active().read_form()
  3081. except AttributeError:
  3082. self.log.debug("on_toolbar_replot(): AttributeError")
  3083. pass
  3084. self.plot_all()
  3085. def on_row_activated(self, index):
  3086. if index.isValid():
  3087. if index.internalPointer().parent_item != self.collection.root_item:
  3088. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3089. def grid_status(self):
  3090. if self.ui.grid_snap_btn.isChecked():
  3091. return 1
  3092. else:
  3093. return 0
  3094. def on_key_over_plot(self, event):
  3095. """
  3096. Callback for the key pressed event when the canvas is focused. Keyboard
  3097. shortcuts are handled here. So far, these are the shortcuts:
  3098. ========== ============================================
  3099. Key Action
  3100. ========== ============================================
  3101. '1' Zoom-fit. Fits the axes limits to the data.
  3102. '2' Zoom-out.
  3103. '3' Zoom-in.
  3104. 'ctrl+m' Toggle on-off the measuring tool.
  3105. ========== ============================================
  3106. :param event: Ignored.
  3107. :return: None
  3108. """
  3109. self.key_modifiers = QtWidgets.QApplication.keyboardModifiers()
  3110. if self.key_modifiers == QtCore.Qt.ControlModifier:
  3111. if event.key == 'A':
  3112. self.on_selectall()
  3113. if event.key == 'C':
  3114. self.on_copy_object()
  3115. if event.key == 'E':
  3116. self.on_fileopenexcellon()
  3117. if event.key == 'G':
  3118. self.on_fileopengerber()
  3119. if event.key == 'N':
  3120. self.on_file_new_click()
  3121. if event.key == 'M':
  3122. self.measurement_tool.run()
  3123. if event.key == 'O':
  3124. self.on_file_openproject()
  3125. if event.key == 'S':
  3126. self.on_file_saveproject()
  3127. # Toggle Plot Area
  3128. if event.key == 'F10':
  3129. self.on_toggle_plotarea()
  3130. return
  3131. elif self.key_modifiers == QtCore.Qt.AltModifier:
  3132. # place holder for further shortcut key
  3133. if event.key == '1':
  3134. self.enable_all_plots()
  3135. if event.key == '2':
  3136. self.disable_all_plots()
  3137. if event.key == '3':
  3138. self.disable_other_plots()
  3139. if event.key == 'C':
  3140. self.calculator_tool.run()
  3141. if event.key == 'D':
  3142. self.dblsidedtool.run()
  3143. if event.key == 'L':
  3144. self.film_tool.run()
  3145. if event.key == 'N':
  3146. self.ncclear_tool.run()
  3147. if event.key == 'P':
  3148. self.paint_tool.run()
  3149. if event.key == 'R':
  3150. self.transform_tool.run()
  3151. if event.key == 'U':
  3152. self.cutout_tool.run()
  3153. if event.key == 'Z':
  3154. self.panelize_tool.run()
  3155. if event.key == 'F10':
  3156. self.on_fullscreen()
  3157. return
  3158. elif self.key_modifiers == QtCore.Qt.ShiftModifier:
  3159. # place holder for further shortcut key
  3160. if event.key == 'C':
  3161. self.on_copy_name()
  3162. # Toggle axis
  3163. if event.key == 'G':
  3164. self.on_toggle_axis()
  3165. # Open Preferences Window
  3166. if event.key == 'P':
  3167. self.on_preferences()
  3168. # Rotate Object by 90 degree CCW
  3169. if event.key == 'R':
  3170. self.on_rotate(silent=True, preset=-90)
  3171. # Run a Script
  3172. if event.key == 'S':
  3173. self.on_filerunscript()
  3174. # Toggle Workspace
  3175. if event.key == 'W':
  3176. self.on_workspace_menu()
  3177. # Skew on X axis
  3178. if event.key == 'X':
  3179. self.on_skewx()
  3180. # Skew on Y axis
  3181. if event.key == 'Y':
  3182. self.on_skewy()
  3183. else:
  3184. if event.key == 'F1':
  3185. webbrowser.open(self.manual_url)
  3186. return
  3187. if event.key == 'F2':
  3188. webbrowser.open(self.video_url)
  3189. return
  3190. if event.key == self.defaults['fit_key']: # 1
  3191. self.on_zoom_fit(None)
  3192. return
  3193. if event.key == self.defaults['zoom_out_key']: # 2
  3194. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  3195. return
  3196. if event.key == self.defaults['zoom_in_key']: # 3
  3197. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  3198. return
  3199. if event.key == 'Delete':
  3200. self.on_delete()
  3201. return
  3202. if event.key == 'Space':
  3203. if self.collection.get_active() is not None:
  3204. self.collection.get_active().ui.plot_cb.toggle()
  3205. self.delete_selection_shape()
  3206. if event.key == 'E':
  3207. self.object2editor()
  3208. if event.key == self.defaults['grid_toggle_key']: # G
  3209. self.ui.grid_snap_btn.trigger()
  3210. if event.key == 'J':
  3211. self.on_jump_to()
  3212. if event.key == 'L':
  3213. self.new_excellon_object()
  3214. if event.key == 'M':
  3215. self.move_tool.toggle()
  3216. return
  3217. if event.key == 'N':
  3218. self.on_new_geometry()
  3219. if event.key == 'O':
  3220. self.on_set_origin()
  3221. if event.key == 'P':
  3222. self.properties_tool.run()
  3223. if event.key == 'Q':
  3224. self.on_toggle_units_click()
  3225. if event.key == 'R':
  3226. self.on_rotate(silent=True, preset=90)
  3227. if event.key == 'S':
  3228. self.on_toggle_shell()
  3229. if event.key == 'V':
  3230. self.on_zoom_fit(None)
  3231. if event.key == 'X':
  3232. self.on_flipx()
  3233. if event.key == 'Y':
  3234. self.on_flipy()
  3235. if event.key == '`':
  3236. self.on_shortcut_list()
  3237. def on_key_release_over_plot(self, event):
  3238. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3239. if modifiers == QtCore.Qt.ControlModifier:
  3240. return
  3241. elif modifiers == QtCore.Qt.AltModifier:
  3242. # place holder for further shortcut key
  3243. return
  3244. elif modifiers == QtCore.Qt.ShiftModifier:
  3245. # place holder for further shortcut key
  3246. return
  3247. else:
  3248. return
  3249. def on_shortcut_list(self):
  3250. # add the tab if it was closed
  3251. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3252. # delete the absolute and relative position and messages in the infobar
  3253. self.ui.position_label.setText("")
  3254. self.ui.rel_position_label.setText("")
  3255. # Switch plot_area to preferences page
  3256. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3257. self.ui.show()
  3258. def on_copy_name(self):
  3259. obj = self.collection.get_active()
  3260. try:
  3261. name = obj.options["name"]
  3262. except AttributeError:
  3263. log.debug("on_copy_name() --> No object selected to copy it's name")
  3264. self.inform.emit("[warning_notcl]No object selected to copy it's name")
  3265. return
  3266. self.clipboard.setText(name)
  3267. self.inform.emit("Name copied on clipboard ...")
  3268. def on_mouse_click_over_plot(self, event):
  3269. """
  3270. Callback for the mouse click event over the plot. This event is generated
  3271. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3272. For details, see: http://matplotlib.org/users/event_handling.html
  3273. Default actions are:
  3274. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3275. :param event: Contains information about the event, like which button
  3276. was clicked, the pixel coordinates and the axes coordinates.
  3277. :return: None
  3278. """
  3279. self.pos = []
  3280. # So it can receive key presses
  3281. self.plotcanvas.vispy_canvas.native.setFocus()
  3282. # Set the mouse button for panning
  3283. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3284. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3285. if self.grid_status() == True:
  3286. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3287. self.app_cursor.enabled = True
  3288. else:
  3289. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3290. self.app_cursor.enabled = False
  3291. try:
  3292. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3293. event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3294. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3295. if event.button == 1:
  3296. # Reset here the relative coordinates so there is a new reference on the click position
  3297. if self.rel_point1 is None:
  3298. self.rel_point1 = self.pos
  3299. else:
  3300. self.rel_point2 = copy(self.rel_point1)
  3301. self.rel_point1 = self.pos
  3302. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3303. if modifiers == QtCore.Qt.ShiftModifier:
  3304. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3305. return
  3306. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3307. # and if it's not selected then it will be selected
  3308. if modifiers == QtCore.Qt.ControlModifier:
  3309. # If there is no active command (self.command_active is None) then we check if we clicked on
  3310. # a object by checking the bounding limits against mouse click position
  3311. if self.command_active is None:
  3312. self.select_objects(key='CTRL')
  3313. else:
  3314. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3315. # checking the bounding limits against mouse click position
  3316. if self.command_active is None:
  3317. self.select_objects()
  3318. self.on_mouse_move_over_plot(event, origin_click=True)
  3319. except Exception as e:
  3320. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3321. def on_double_click_over_plot(self, event):
  3322. # make double click work only for the LMB
  3323. if event.button == 1:
  3324. if not self.collection.get_selected():
  3325. pass
  3326. else:
  3327. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3328. #delete the selection shape(S) as it may be in the way
  3329. self.delete_selection_shape()
  3330. def on_mouse_move_over_plot(self, event, origin_click=None):
  3331. """
  3332. Callback for the mouse motion event over the plot. This event is generated
  3333. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3334. For details, see: http://matplotlib.org/users/event_handling.html
  3335. :param event: Contains information about the event.
  3336. :param origin_click
  3337. :return: None
  3338. """
  3339. # So it can receive key presses
  3340. self.plotcanvas.vispy_canvas.native.setFocus()
  3341. self.pos_jump = event.pos
  3342. if origin_click is True:
  3343. pass
  3344. else:
  3345. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3346. if event.button == 2:
  3347. self.panning_action = True
  3348. return
  3349. else:
  3350. self.panning_action = False
  3351. if self.rel_point1 is not None:
  3352. try: # May fail in case mouse not within axes
  3353. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3354. if self.grid_status():
  3355. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3356. self.app_cursor.enabled = True
  3357. # Update cursor
  3358. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3359. else:
  3360. pos = (pos_canvas[0], pos_canvas[1])
  3361. self.app_cursor.enabled = False
  3362. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3363. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3364. dx = pos[0] - self.rel_point1[0]
  3365. dy = pos[1] - self.rel_point1[1]
  3366. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3367. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3368. self.mouse = [pos[0], pos[1]]
  3369. # if the mouse is moved and the LMB is clicked then the action is a selection
  3370. if event.is_dragging == 1 and event.button == 1:
  3371. self.delete_selection_shape()
  3372. if dx < 0:
  3373. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3374. face_color=self.defaults['global_alt_sel_fill'])
  3375. self.selection_type = False
  3376. else:
  3377. self.draw_moving_selection_shape(self.pos, pos)
  3378. self.selection_type = True
  3379. # delete the status message on mouse move
  3380. # self.inform.emit("")
  3381. except:
  3382. self.ui.position_label.setText("")
  3383. self.ui.rel_position_label.setText("")
  3384. self.mouse = None
  3385. def on_mouse_click_release_over_plot(self, event):
  3386. """
  3387. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3388. and has been registered in ''self.__init__()''.
  3389. :param event: contains information about the event.
  3390. :return:
  3391. """
  3392. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3393. if self.grid_status():
  3394. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3395. else:
  3396. pos = (pos_canvas[0], pos_canvas[1])
  3397. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3398. # canvas menu
  3399. try:
  3400. if event.button == 2: # right click
  3401. if self.panning_action is True:
  3402. self.panning_action = False
  3403. else:
  3404. self.cursor = QtGui.QCursor()
  3405. self.ui.popMenu.popup(self.cursor.pos())
  3406. except Exception as e:
  3407. log.warning("Error: %s" % str(e))
  3408. return
  3409. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3410. # selection and then select a type of selection ("enclosing" or "touching")
  3411. try:
  3412. if event.button == 1: # left click
  3413. if self.selection_type is not None:
  3414. self.selection_area_handler(self.pos, pos, self.selection_type)
  3415. self.selection_type = None
  3416. except Exception as e:
  3417. log.warning("Error: %s" % str(e))
  3418. return
  3419. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3420. """
  3421. :param start_pos: mouse position when the selection LMB click was done
  3422. :param end_pos: mouse position when the left mouse button is released
  3423. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3424. :return:
  3425. """
  3426. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3427. self.delete_selection_shape()
  3428. for obj in self.collection.get_list():
  3429. try:
  3430. # select the object(s) only if it is enabled (plotted)
  3431. if obj.options['plot']:
  3432. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3433. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3434. if sel_type is True:
  3435. if poly_obj.within(poly_selection):
  3436. # create the selection box around the selected object
  3437. self.draw_selection_shape(obj)
  3438. self.collection.set_active(obj.options['name'])
  3439. else:
  3440. if poly_selection.intersects(poly_obj):
  3441. # create the selection box around the selected object
  3442. self.draw_selection_shape(obj)
  3443. self.collection.set_active(obj.options['name'])
  3444. except:
  3445. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3446. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3447. # In this case poly_obj creation (see above) will fail
  3448. pass
  3449. def select_objects(self, key=None):
  3450. # list where we store the overlapped objects under our mouse left click position
  3451. objects_under_the_click_list = []
  3452. # Populate the list with the overlapped objects on the click position
  3453. curr_x, curr_y = self.pos
  3454. for obj in self.all_objects_list:
  3455. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3456. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3457. if obj.options['name'] not in objects_under_the_click_list:
  3458. if obj.options['plot']:
  3459. # add objects to the objects_under_the_click list only if the object is plotted
  3460. # (active and not disabled)
  3461. objects_under_the_click_list.append(obj.options['name'])
  3462. try:
  3463. # If there is no element in the overlapped objects list then make everyone inactive
  3464. # because we selected "nothing"
  3465. if not objects_under_the_click_list:
  3466. self.collection.set_all_inactive()
  3467. # delete the possible selection box around a possible selected object
  3468. self.delete_selection_shape()
  3469. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3470. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3471. else:
  3472. # case when there is only an object under the click and we toggle it
  3473. if len(objects_under_the_click_list) == 1:
  3474. if self.collection.get_active() is None :
  3475. self.collection.set_active(objects_under_the_click_list[0])
  3476. # create the selection box around the selected object
  3477. curr_sel_obj = self.collection.get_active()
  3478. self.draw_selection_shape(curr_sel_obj)
  3479. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3480. self.collection.set_all_inactive()
  3481. self.delete_selection_shape()
  3482. self.collection.set_active(objects_under_the_click_list[0])
  3483. # create the selection box around the selected object
  3484. curr_sel_obj = self.collection.get_active()
  3485. self.draw_selection_shape(curr_sel_obj)
  3486. else:
  3487. self.collection.set_all_inactive()
  3488. self.delete_selection_shape()
  3489. else:
  3490. # If there is no selected object
  3491. # make active the first element of the overlapped objects list
  3492. if self.collection.get_active() is None:
  3493. self.collection.set_active(objects_under_the_click_list[0])
  3494. name_sel_obj = self.collection.get_active().options['name']
  3495. # In case that there is a selected object but it is not in the overlapped object list
  3496. # make that object inactive and activate the first element in the overlapped object list
  3497. if name_sel_obj not in objects_under_the_click_list:
  3498. self.collection.set_inactive(name_sel_obj)
  3499. name_sel_obj = objects_under_the_click_list[0]
  3500. self.collection.set_active(name_sel_obj)
  3501. else:
  3502. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3503. self.collection.set_all_inactive()
  3504. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) % len(objects_under_the_click_list)])
  3505. curr_sel_obj = self.collection.get_active()
  3506. # delete the possible selection box around a possible selected object
  3507. self.delete_selection_shape()
  3508. # create the selection box around the selected object
  3509. self.draw_selection_shape(curr_sel_obj)
  3510. # for obj in self.collection.get_list():
  3511. # obj.plot()
  3512. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3513. # TODO: on selected objects change the object colors and do not draw the selection box
  3514. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3515. except Exception as e:
  3516. log.error("[error] Something went bad. %s" % str(e))
  3517. return
  3518. def delete_selection_shape(self):
  3519. self.move_tool.sel_shapes.clear()
  3520. self.move_tool.sel_shapes.redraw()
  3521. def draw_selection_shape(self, sel_obj):
  3522. """
  3523. :param sel_obj: the object for which the selection shape must be drawn
  3524. :return:
  3525. """
  3526. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3527. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3528. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3529. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3530. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3531. #blue_t = Color('blue')
  3532. blue_t = Color(self.defaults['global_sel_fill'])
  3533. blue_t.alpha = 0.3
  3534. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3535. face_color=blue_t, update=True, layer=0, tolerance=None))
  3536. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3537. """
  3538. :param old_coords: old coordinates
  3539. :param coords: new coordinates
  3540. :return:
  3541. """
  3542. if 'color' in kwargs:
  3543. color = kwargs['color']
  3544. else:
  3545. color = self.defaults['global_sel_line']
  3546. if 'face_color' in kwargs:
  3547. face_color = kwargs['face_color']
  3548. else:
  3549. face_color = self.defaults['global_sel_fill']
  3550. x0, y0 = old_coords
  3551. x1, y1 = coords
  3552. pt1 = (x0, y0)
  3553. pt2 = (x1, y0)
  3554. pt3 = (x1, y1)
  3555. pt4 = (x0, y1)
  3556. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3557. color_t = Color(face_color)
  3558. color_t.alpha = 0.3
  3559. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3560. layer=0, tolerance=None)
  3561. def on_file_new_click(self):
  3562. if self.collection.get_list():
  3563. msgbox = QtWidgets.QMessageBox()
  3564. # msgbox.setText("<B>Save changes ...</B>")
  3565. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3566. "Creating a New project will delete them.\n"
  3567. "Do you want to Save the project?")
  3568. msgbox.setWindowTitle("Save changes")
  3569. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3570. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3571. QtWidgets.QMessageBox.No)
  3572. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3573. response = msgbox.exec_()
  3574. if response == QtWidgets.QMessageBox.Yes:
  3575. self.on_file_saveprojectas()
  3576. elif response == QtWidgets.QMessageBox.Cancel:
  3577. return
  3578. self.on_file_new()
  3579. else:
  3580. self.on_file_new()
  3581. self.inform.emit("[success] New Project created...")
  3582. def on_file_new(self):
  3583. """
  3584. Callback for menu item File->New. Returns the application to its
  3585. startup state. This method is thread-safe.
  3586. :return: None
  3587. """
  3588. self.report_usage("on_file_new")
  3589. # Remove everything from memory
  3590. App.log.debug("on_file_new()")
  3591. # Clear pool
  3592. self.clear_pool()
  3593. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3594. self.init_tcl()
  3595. self.delete_selection_shape()
  3596. self.collection.delete_all()
  3597. self.setup_component_editor()
  3598. # Clear project filename
  3599. self.project_filename = None
  3600. # Load the application defaults
  3601. self.load_defaults(filename='current_defaults')
  3602. # Re-fresh project options
  3603. self.on_options_app2project()
  3604. # Init Tools
  3605. self.init_tools()
  3606. # take the focus of the Notebook on Project Tab.
  3607. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3608. def obj_properties(self):
  3609. self.properties_tool.run()
  3610. def obj_move(self):
  3611. self.move_tool.run()
  3612. def on_fileopengerber(self):
  3613. """
  3614. File menu callback for opening a Gerber.
  3615. :return: None
  3616. """
  3617. self.report_usage("on_fileopengerber")
  3618. App.log.debug("on_fileopengerber()")
  3619. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3620. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3621. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3622. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3623. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3624. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3625. "Allegro Files (*.art);;" \
  3626. "Mentor Files (*.pho *.gdo);;" \
  3627. "All Files (*.*)"
  3628. try:
  3629. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  3630. directory=self.get_last_folder(), filter=_filter_)
  3631. except TypeError:
  3632. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  3633. filenames = [str(filename) for filename in filenames]
  3634. if len(filenames) == 0:
  3635. self.inform.emit("[warning_notcl]Open Gerber cancelled.")
  3636. else:
  3637. for filename in filenames:
  3638. if filename != '':
  3639. self.worker_task.emit({'fcn': self.open_gerber,
  3640. 'params': [filename]})
  3641. def on_fileopengerber_follow(self):
  3642. """
  3643. File menu callback for opening a Gerber.
  3644. :return: None
  3645. """
  3646. self.report_usage("on_fileopengerber_follow")
  3647. App.log.debug("on_fileopengerber_follow()")
  3648. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3649. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3650. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3651. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3652. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3653. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3654. "Allegro Files (*.art);;" \
  3655. "Mentor Files (*.pho *.gdo);;" \
  3656. "All Files (*.*)"
  3657. try:
  3658. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  3659. directory=self.get_last_folder(), filter=_filter_)
  3660. except TypeError:
  3661. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  3662. # The Qt methods above will return a QString which can cause problems later.
  3663. # So far json.dump() will fail to serialize it.
  3664. # TODO: Improve the serialization methods and remove this fix.
  3665. filename = str(filename)
  3666. follow = True
  3667. if filename == "":
  3668. self.inform.emit("[warning_notcl]Open Gerber-Follow cancelled.")
  3669. else:
  3670. self.worker_task.emit({'fcn': self.open_gerber,
  3671. 'params': [filename, follow]})
  3672. def on_fileopenexcellon(self):
  3673. """
  3674. File menu callback for opening an Excellon file.
  3675. :return: None
  3676. """
  3677. self.report_usage("on_fileopenexcellon")
  3678. App.log.debug("on_fileopenexcellon()")
  3679. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  3680. "All Files (*.*)"
  3681. try:
  3682. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  3683. directory=self.get_last_folder(), filter=_filter_)
  3684. except TypeError:
  3685. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  3686. filenames = [str(filename) for filename in filenames]
  3687. if len(filenames) == 0:
  3688. self.inform.emit("[warning_notcl]Open Excellon cancelled.")
  3689. else:
  3690. for filename in filenames:
  3691. if filename != '':
  3692. self.worker_task.emit({'fcn': self.open_excellon,
  3693. 'params': [filename]})
  3694. def on_fileopengcode(self):
  3695. """
  3696. File menu call back for opening gcode.
  3697. :return: None
  3698. """
  3699. self.report_usage("on_fileopengcode")
  3700. App.log.debug("on_fileopengcode()")
  3701. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  3702. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  3703. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  3704. "All Files (*.*)"
  3705. try:
  3706. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  3707. directory=self.get_last_folder(), filter=_filter_)
  3708. except TypeError:
  3709. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  3710. filenames = [str(filename) for filename in filenames]
  3711. if len(filenames) == 0:
  3712. self.inform.emit("[warning_notcl]Open G-Code cancelled.")
  3713. else:
  3714. for filename in filenames:
  3715. if filename != '':
  3716. self.worker_task.emit({'fcn': self.open_gcode,
  3717. 'params': [filename]})
  3718. def on_file_openproject(self):
  3719. """
  3720. File menu callback for opening a project.
  3721. :return: None
  3722. """
  3723. self.report_usage("on_file_openproject")
  3724. App.log.debug("on_file_openproject()")
  3725. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  3726. try:
  3727. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  3728. directory=self.get_last_folder(), filter=_filter_)
  3729. except TypeError:
  3730. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  3731. # The Qt methods above will return a QString which can cause problems later.
  3732. # So far json.dump() will fail to serialize it.
  3733. # TODO: Improve the serialization methods and remove this fix.
  3734. filename = str(filename)
  3735. if filename == "":
  3736. self.inform.emit("[warning_notcl]Open Project cancelled.")
  3737. else:
  3738. # self.worker_task.emit({'fcn': self.open_project,
  3739. # 'params': [filename]})
  3740. # The above was failing because open_project() is not
  3741. # thread safe. The new_project()
  3742. self.open_project(filename)
  3743. def on_file_exportsvg(self):
  3744. """
  3745. Callback for menu item File->Export SVG.
  3746. :return: None
  3747. """
  3748. self.report_usage("on_file_exportsvg")
  3749. App.log.debug("on_file_exportsvg()")
  3750. obj = self.collection.get_active()
  3751. if obj is None:
  3752. self.inform.emit("WARNING: No object selected.")
  3753. msg = "Please Select a Geometry object to export"
  3754. msgbox = QtWidgets.QMessageBox()
  3755. msgbox.setInformativeText(msg)
  3756. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3757. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3758. msgbox.exec_()
  3759. return
  3760. # Check for more compatible types and add as required
  3761. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  3762. and not isinstance(obj, FlatCAMExcellon)):
  3763. msg = "[error_notcl] Only Geometry, Gerber and CNCJob objects can be used."
  3764. msgbox = QtWidgets.QMessageBox()
  3765. msgbox.setInformativeText(msg)
  3766. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3767. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3768. msgbox.exec_()
  3769. return
  3770. name = self.collection.get_active().options["name"]
  3771. filter = "SVG File (*.svg);;All Files (*.*)"
  3772. try:
  3773. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG",
  3774. directory=self.get_last_save_folder(), filter=filter)
  3775. except TypeError:
  3776. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  3777. filename = str(filename)
  3778. if filename == "":
  3779. self.inform.emit("[warning_notcl]Export SVG cancelled.")
  3780. return
  3781. else:
  3782. self.export_svg(name, filename)
  3783. self.file_saved.emit("SVG", filename)
  3784. def on_file_exportpng(self):
  3785. self.report_usage("on_file_exportpng")
  3786. App.log.debug("on_file_exportpng()")
  3787. image = _screenshot()
  3788. data = np.asarray(image)
  3789. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  3790. self.inform.emit('[[warning_notcl]] Data must be a 3D array with last dimension 3 or 4')
  3791. return
  3792. filter = "PNG File (*.png);;All Files (*.*)"
  3793. try:
  3794. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image",
  3795. directory=self.get_last_save_folder(), filter=filter)
  3796. except TypeError:
  3797. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter)
  3798. filename = str(filename)
  3799. if filename == "":
  3800. self.inform.emit("Export PNG cancelled.")
  3801. return
  3802. else:
  3803. write_png(filename, data)
  3804. self.file_saved.emit("png", filename)
  3805. def on_file_exportexcellon(self, altium_format=None):
  3806. """
  3807. Callback for menu item File->Export SVG.
  3808. :return: None
  3809. """
  3810. self.report_usage("on_file_exportexcellon")
  3811. App.log.debug("on_file_exportexcellon()")
  3812. obj = self.collection.get_active()
  3813. if obj is None:
  3814. self.inform.emit("[warning_notcl] No object selected.")
  3815. msg = "Please Select an Excellon object to export"
  3816. msgbox = QtWidgets.QMessageBox()
  3817. msgbox.setInformativeText(msg)
  3818. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3819. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3820. msgbox.exec_()
  3821. return
  3822. # Check for more compatible types and add as required
  3823. if not isinstance(obj, FlatCAMExcellon):
  3824. msg = "[warning_notcl] Only Excellon objects can be used."
  3825. msgbox = QtWidgets.QMessageBox()
  3826. msgbox.setInformativeText(msg)
  3827. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3828. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3829. msgbox.exec_()
  3830. return
  3831. name = self.collection.get_active().options["name"]
  3832. filter = "Excellon File (*.drl);;Excellon File (*.txt);;All Files (*.*)"
  3833. try:
  3834. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon",
  3835. directory=self.get_last_save_folder(), filter=filter)
  3836. except TypeError:
  3837. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  3838. filename = str(filename)
  3839. if filename == "":
  3840. self.inform.emit("[warning_notcl]Export Excellon cancelled.")
  3841. return
  3842. else:
  3843. if altium_format == None:
  3844. self.export_excellon(name, filename)
  3845. self.file_saved.emit("Excellon", filename)
  3846. else:
  3847. self.export_excellon(name, filename, altium_format=True)
  3848. self.file_saved.emit("Excellon", filename)
  3849. def on_file_exportdxf(self):
  3850. """
  3851. Callback for menu item File->Export DXF.
  3852. :return: None
  3853. """
  3854. self.report_usage("on_file_exportdxf")
  3855. App.log.debug("on_file_exportdxf()")
  3856. obj = self.collection.get_active()
  3857. if obj is None:
  3858. self.inform.emit("W[warning_notcl] No object selected.")
  3859. msg = "Please Select a Geometry object to export"
  3860. msgbox = QtWidgets.QMessageBox()
  3861. msgbox.setInformativeText(msg)
  3862. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3863. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3864. msgbox.exec_()
  3865. return
  3866. # Check for more compatible types and add as required
  3867. if not isinstance(obj, FlatCAMGeometry):
  3868. msg = "[error_notcl] Only Geometry objects can be used."
  3869. msgbox = QtWidgets.QMessageBox()
  3870. msgbox.setInformativeText(msg)
  3871. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3872. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3873. msgbox.exec_()
  3874. return
  3875. name = self.collection.get_active().options["name"]
  3876. filter = "DXF File (*.DXF);;All Files (*.*)"
  3877. try:
  3878. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF",
  3879. directory=self.get_last_save_folder(), filter=filter)
  3880. except TypeError:
  3881. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  3882. filename = str(filename)
  3883. if filename == "":
  3884. self.inform.emit("[warning_notcl]Export DXF cancelled.")
  3885. return
  3886. else:
  3887. self.export_dxf(name, filename)
  3888. self.file_saved.emit("DXF", filename)
  3889. def on_file_importsvg(self, type_of_obj):
  3890. """
  3891. Callback for menu item File->Import SVG.
  3892. :param type_of_obj: to import the SVG as Geometry or as Gerber
  3893. :type type_of_obj: str
  3894. :return: None
  3895. """
  3896. self.report_usage("on_file_importsvg")
  3897. App.log.debug("on_file_importsvg()")
  3898. filter = "SVG File (*.svg);;All Files (*.*)"
  3899. try:
  3900. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  3901. directory=self.get_last_folder(), filter=filter)
  3902. except TypeError:
  3903. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  3904. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3905. type_of_obj = "geometry"
  3906. filenames = [str(filename) for filename in filenames]
  3907. if len(filenames) == 0:
  3908. self.inform.emit("[warning_notcl]Open SVG cancelled.")
  3909. else:
  3910. for filename in filenames:
  3911. if filename != '':
  3912. self.worker_task.emit({'fcn': self.import_svg,
  3913. 'params': [filename, type_of_obj]})
  3914. def on_file_importdxf(self, type_of_obj):
  3915. """
  3916. Callback for menu item File->Import DXF.
  3917. :param type_of_obj: to import the DXF as Geometry or as Gerber
  3918. :type type_of_obj: str
  3919. :return: None
  3920. """
  3921. self.report_usage("on_file_importdxf")
  3922. App.log.debug("on_file_importdxf()")
  3923. filter = "DXF File (*.DXF);;All Files (*.*)"
  3924. try:
  3925. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  3926. directory=self.get_last_folder(), filter=filter)
  3927. except TypeError:
  3928. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  3929. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3930. type_of_obj = "geometry"
  3931. filenames = [str(filename) for filename in filenames]
  3932. if len(filenames) == 0:
  3933. self.inform.emit("[warning_notcl]Open DXF cancelled.")
  3934. else:
  3935. for filename in filenames:
  3936. if filename != '':
  3937. self.worker_task.emit({'fcn': self.import_dxf,
  3938. 'params': [filename, type_of_obj]})
  3939. def on_filerunscript(self):
  3940. """
  3941. File menu callback for loading and running a TCL script.
  3942. :return: None
  3943. """
  3944. self.report_usage("on_filerunscript")
  3945. App.log.debug("on_file_runscript()")
  3946. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  3947. try:
  3948. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  3949. directory=self.get_last_folder(), filter=_filter_)
  3950. except TypeError:
  3951. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  3952. # The Qt methods above will return a QString which can cause problems later.
  3953. # So far json.dump() will fail to serialize it.
  3954. # TODO: Improve the serialization methods and remove this fix.
  3955. filename = str(filename)
  3956. if filename == "":
  3957. self.inform.emit("[warning_notcl]Open TCL script cancelled.")
  3958. else:
  3959. try:
  3960. with open(filename, "r") as tcl_script:
  3961. cmd_line_shellfile_content = tcl_script.read()
  3962. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  3963. except Exception as ext:
  3964. print("ERROR: ", ext)
  3965. sys.exit(2)
  3966. def on_file_saveproject(self):
  3967. """
  3968. Callback for menu item File->Save Project. Saves the project to
  3969. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  3970. if set to None. The project is saved by calling ``self.save_project()``.
  3971. :return: None
  3972. """
  3973. self.report_usage("on_file_saveproject")
  3974. if self.project_filename is None:
  3975. self.on_file_saveprojectas()
  3976. else:
  3977. self.worker_task.emit({'fcn': self.save_project,
  3978. 'params': [self.project_filename]})
  3979. # self.save_project(self.project_filename)
  3980. self.file_opened.emit("project", self.project_filename)
  3981. self.file_saved.emit("project", self.project_filename)
  3982. def on_file_saveprojectas(self, make_copy=False, thread=True):
  3983. """
  3984. Callback for menu item File->Save Project As... Opens a file
  3985. chooser and saves the project to the given file via
  3986. ``self.save_project()``.
  3987. :return: None
  3988. """
  3989. self.report_usage("on_file_saveprojectas")
  3990. filter = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  3991. try:
  3992. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...",
  3993. directory=self.get_last_save_folder(), filter=filter)
  3994. except TypeError:
  3995. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter)
  3996. filename = str(filename)
  3997. if filename == '':
  3998. self.inform.emit("[warning_notcl]Save Project cancelled.")
  3999. return
  4000. try:
  4001. f = open(filename, 'r')
  4002. f.close()
  4003. exists = True
  4004. except IOError:
  4005. exists = False
  4006. msg = "File exists. Overwrite?"
  4007. if exists:
  4008. msgbox = QtWidgets.QMessageBox()
  4009. msgbox.setInformativeText(msg)
  4010. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  4011. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  4012. result = msgbox.exec_()
  4013. if result ==QtWidgets.QMessageBox.Cancel:
  4014. return
  4015. if thread is True:
  4016. self.worker_task.emit({'fcn': self.save_project,
  4017. 'params': [filename]})
  4018. else:
  4019. self.save_project(filename)
  4020. # self.save_project(filename)
  4021. self.file_opened.emit("project", filename)
  4022. self.file_saved.emit("project", filename)
  4023. if not make_copy:
  4024. self.project_filename = filename
  4025. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4026. """
  4027. Exports a Geometry Object to an SVG file.
  4028. :param filename: Path to the SVG file to save to.
  4029. :return:
  4030. """
  4031. if filename is None:
  4032. filename = self.defaults["global_last_save_folder"]
  4033. self.log.debug("export_svg()")
  4034. try:
  4035. obj = self.collection.get_by_name(str(obj_name))
  4036. except:
  4037. # TODO: The return behavior has not been established... should raise exception?
  4038. return "Could not retrieve object: %s" % obj_name
  4039. with self.proc_container.new("Exporting SVG") as proc:
  4040. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4041. # Determine bounding area for svg export
  4042. bounds = obj.bounds()
  4043. size = obj.size()
  4044. # Convert everything to strings for use in the xml doc
  4045. svgwidth = str(size[0])
  4046. svgheight = str(size[1])
  4047. minx = str(bounds[0])
  4048. miny = str(bounds[1] - size[1])
  4049. uom = obj.units.lower()
  4050. # Add a SVG Header and footer to the svg output from shapely
  4051. # The transform flips the Y Axis so that everything renders
  4052. # properly within svg apps such as inkscape
  4053. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4054. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4055. svg_header += 'width="' + svgwidth + uom + '" '
  4056. svg_header += 'height="' + svgheight + uom + '" '
  4057. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4058. svg_header += '<g transform="scale(1,-1)">'
  4059. svg_footer = '</g> </svg>'
  4060. svg_elem = svg_header + exported_svg + svg_footer
  4061. # Parse the xml through a xml parser just to add line feeds
  4062. # and to make it look more pretty for the output
  4063. svgcode = parse_xml_string(svg_elem)
  4064. with open(filename, 'w') as fp:
  4065. fp.write(svgcode.toprettyxml())
  4066. self.file_saved.emit("SVG", filename)
  4067. self.inform.emit("[success] SVG file exported to " + filename)
  4068. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4069. """
  4070. Exports a Geometry Object to an SVG file in negative.
  4071. :param filename: Path to the SVG file to save to.
  4072. :param: use_thread: If True use threads
  4073. :type: Bool
  4074. :return:
  4075. """
  4076. if filename is None:
  4077. filename = self.defaults["global_last_save_folder"]
  4078. self.log.debug("export_svg() negative")
  4079. try:
  4080. obj = self.collection.get_by_name(str(obj_name))
  4081. except:
  4082. # TODO: The return behavior has not been established... should raise exception?
  4083. return "Could not retrieve object: %s" % obj_name
  4084. try:
  4085. box = self.collection.get_by_name(str(box_name))
  4086. except:
  4087. # TODO: The return behavior has not been established... should raise exception?
  4088. return "Could not retrieve object: %s" % box_name
  4089. if box is None:
  4090. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  4091. box = obj
  4092. def make_negative_film():
  4093. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4094. self.progress.emit(40)
  4095. # Determine bounding area for svg export
  4096. bounds = box.bounds()
  4097. size = box.size()
  4098. uom = obj.units.lower()
  4099. # Convert everything to strings for use in the xml doc
  4100. svgwidth = str(size[0] + (2 * boundary))
  4101. svgheight = str(size[1] + (2 * boundary))
  4102. minx = str(bounds[0] - boundary)
  4103. miny = str(bounds[1] + boundary + size[1])
  4104. miny_rect = str(bounds[1] - boundary)
  4105. # Add a SVG Header and footer to the svg output from shapely
  4106. # The transform flips the Y Axis so that everything renders
  4107. # properly within svg apps such as inkscape
  4108. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4109. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4110. svg_header += 'width="' + svgwidth + uom + '" '
  4111. svg_header += 'height="' + svgheight + uom + '" '
  4112. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4113. svg_header += '>'
  4114. svg_header += '<g transform="scale(1,-1)">'
  4115. svg_footer = '</g> </svg>'
  4116. self.progress.emit(60)
  4117. # Change the attributes of the exported SVG
  4118. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4119. # We set opacity to maximum
  4120. # We set the color to WHITE
  4121. root = ET.fromstring(exported_svg)
  4122. for child in root:
  4123. child.set('fill', '#FFFFFF')
  4124. child.set('opacity', '1.0')
  4125. child.set('stroke', '#FFFFFF')
  4126. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4127. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4128. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4129. first_svg_elem_tag = 'rect'
  4130. first_svg_elem_attribs = {
  4131. 'x': minx,
  4132. 'y': miny_rect,
  4133. 'width': svgwidth,
  4134. 'height': svgheight,
  4135. 'id': 'neg_rect',
  4136. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4137. }
  4138. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4139. exported_svg = ET.tostring(root)
  4140. svg_elem = svg_header + str(exported_svg) + svg_footer
  4141. self.progress.emit(80)
  4142. # Parse the xml through a xml parser just to add line feeds
  4143. # and to make it look more pretty for the output
  4144. doc = parse_xml_string(svg_elem)
  4145. with open(filename, 'w') as fp:
  4146. fp.write(doc.toprettyxml())
  4147. self.progress.emit(100)
  4148. self.file_saved.emit("SVG", filename)
  4149. self.inform.emit("[success] SVG file exported to " + filename)
  4150. if use_thread is True:
  4151. proc = self.proc_container.new("Generating Film ... Please wait.")
  4152. def job_thread_film(app_obj):
  4153. try:
  4154. make_negative_film()
  4155. except Exception as e:
  4156. proc.done()
  4157. return
  4158. proc.done()
  4159. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4160. else:
  4161. make_negative_film()
  4162. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4163. """
  4164. Exports a Geometry Object to an SVG file in negative.
  4165. :param filename: Path to the SVG file to save to.
  4166. :param: use_thread: If True use threads
  4167. :type: Bool
  4168. :return:
  4169. """
  4170. if filename is None:
  4171. filename = self.defaults["global_last_save_folder"]
  4172. self.log.debug("export_svg() black")
  4173. try:
  4174. obj = self.collection.get_by_name(str(obj_name))
  4175. except:
  4176. # TODO: The return behavior has not been established... should raise exception?
  4177. return "Could not retrieve object: %s" % obj_name
  4178. try:
  4179. box = self.collection.get_by_name(str(box_name))
  4180. except:
  4181. # TODO: The return behavior has not been established... should raise exception?
  4182. return "Could not retrieve object: %s" % box_name
  4183. if box is None:
  4184. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  4185. box = obj
  4186. def make_black_film():
  4187. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4188. self.progress.emit(40)
  4189. # Change the attributes of the exported SVG
  4190. # We don't need stroke-width
  4191. # We set opacity to maximum
  4192. # We set the colour to WHITE
  4193. root = ET.fromstring(exported_svg)
  4194. for child in root:
  4195. child.set('fill', '#000000')
  4196. child.set('opacity', '1.0')
  4197. child.set('stroke', '#000000')
  4198. exported_svg = ET.tostring(root)
  4199. # Determine bounding area for svg export
  4200. bounds = box.bounds()
  4201. size = box.size()
  4202. # This contain the measure units
  4203. uom = obj.units.lower()
  4204. # Define a boundary around SVG of about 1.0mm (~39mils)
  4205. if uom in "mm":
  4206. boundary = 1.0
  4207. else:
  4208. boundary = 0.0393701
  4209. self.progress.emit(80)
  4210. # Convert everything to strings for use in the xml doc
  4211. svgwidth = str(size[0] + (2 * boundary))
  4212. svgheight = str(size[1] + (2 * boundary))
  4213. minx = str(bounds[0] - boundary)
  4214. miny = str(bounds[1] + boundary + size[1])
  4215. self.log.debug(minx)
  4216. self.log.debug(miny)
  4217. # Add a SVG Header and footer to the svg output from shapely
  4218. # The transform flips the Y Axis so that everything renders
  4219. # properly within svg apps such as inkscape
  4220. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4221. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4222. svg_header += 'width="' + svgwidth + uom + '" '
  4223. svg_header += 'height="' + svgheight + uom + '" '
  4224. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4225. svg_header += '>'
  4226. svg_header += '<g transform="scale(1,-1)">'
  4227. svg_footer = '</g> </svg>'
  4228. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4229. self.progress.emit(90)
  4230. # Parse the xml through a xml parser just to add line feeds
  4231. # and to make it look more pretty for the output
  4232. doc = parse_xml_string(svg_elem)
  4233. with open(filename, 'w') as fp:
  4234. fp.write(doc.toprettyxml())
  4235. self.progress.emit(100)
  4236. self.file_saved.emit("SVG", filename)
  4237. self.inform.emit("[success] SVG file exported to " + filename)
  4238. if use_thread is True:
  4239. proc = self.proc_container.new("Generating Film ... Please wait.")
  4240. def job_thread_film(app_obj):
  4241. try:
  4242. make_black_film()
  4243. except Exception as e:
  4244. proc.done()
  4245. return
  4246. proc.done()
  4247. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4248. else:
  4249. make_black_film()
  4250. def export_excellon(self, obj_name, filename, altium_format=None, use_thread=True):
  4251. """
  4252. Exports a Geometry Object to an Excellon file.
  4253. :param filename: Path to the Excellon file to save to.
  4254. :return:
  4255. """
  4256. if filename is None:
  4257. filename = self.defaults["global_last_save_folder"]
  4258. self.log.debug("export_excellon()")
  4259. format_exc = ';FILE_FORMAT=2:4\n'
  4260. units = ''
  4261. try:
  4262. obj = self.collection.get_by_name(str(obj_name))
  4263. except:
  4264. # TODO: The return behavior has not been established... should raise exception?
  4265. return "Could not retrieve object: %s" % obj_name
  4266. # updated units
  4267. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4268. if units == 'IN' or units == 'INCH':
  4269. units = 'INCH'
  4270. elif units == 'MM' or units == 'METRIC':
  4271. units ='METRIC'
  4272. def make_excellon():
  4273. try:
  4274. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4275. header = 'M48\n'
  4276. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4277. (str(self.app.version), str(self.app.version_date))
  4278. header += ';Filename: %s' % str(obj_name) + '\n'
  4279. header += ';Created on : %s' % time_str + '\n'
  4280. if altium_format == None:
  4281. has_slots, excellon_code = obj.export_excellon()
  4282. header += units + '\n'
  4283. for tool in obj.tools:
  4284. if units == 'METRIC':
  4285. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.2f' % float(obj.tools[tool]['C']) + '\n'
  4286. else:
  4287. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4288. else:
  4289. has_slots, excellon_code = obj.export_excellon_altium()
  4290. header += 'INCH,LZ\n'
  4291. header += format_exc
  4292. for tool in obj.tools:
  4293. if units == 'METRIC':
  4294. header += 'T' + str(tool) + 'F00S00' + 'C' + \
  4295. '%.4f' % (float(obj.tools[tool]['C']) / 25.4) + '\n'
  4296. else:
  4297. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4298. header += '%\n'
  4299. footer = 'M30\n'
  4300. exported_excellon = header
  4301. exported_excellon += excellon_code
  4302. exported_excellon += footer
  4303. with open(filename, 'w') as fp:
  4304. fp.write(exported_excellon)
  4305. self.file_saved.emit("Excellon", filename)
  4306. self.inform.emit("[success] Excellon file exported to " + filename)
  4307. except:
  4308. return 'fail'
  4309. if use_thread is True:
  4310. with self.proc_container.new("Exporting Excellon") as proc:
  4311. def job_thread_exc(app_obj):
  4312. ret = make_excellon()
  4313. if ret == 'fail':
  4314. self.inform.emit('[error_notcl] Could not export Excellon file.')
  4315. return
  4316. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4317. else:
  4318. ret = make_excellon()
  4319. if ret == 'fail':
  4320. self.inform.emit('[error_notcl] Could not export Excellon file.')
  4321. return
  4322. def export_dxf(self, obj_name, filename, use_thread=True):
  4323. """
  4324. Exports a Geometry Object to an DXF file.
  4325. :param filename: Path to the DXF file to save to.
  4326. :return:
  4327. """
  4328. if filename is None:
  4329. filename = self.defaults["global_last_save_folder"]
  4330. self.log.debug("export_dxf()")
  4331. format_exc = ''
  4332. units = ''
  4333. try:
  4334. obj = self.collection.get_by_name(str(obj_name))
  4335. except:
  4336. # TODO: The return behavior has not been established... should raise exception?
  4337. return "Could not retrieve object: %s" % obj_name
  4338. # updated units
  4339. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4340. if units == 'IN' or units == 'INCH':
  4341. units = 'INCH'
  4342. elif units == 'MM' or units == 'METIRC':
  4343. units ='METRIC'
  4344. def make_dxf():
  4345. try:
  4346. dxf_code = obj.export_dxf()
  4347. dxf_code.saveas(filename)
  4348. self.file_saved.emit("DXF", filename)
  4349. self.inform.emit("[success] DXF file exported to " + filename)
  4350. except:
  4351. return 'fail'
  4352. if use_thread is True:
  4353. with self.proc_container.new("Exporting DXF") as proc:
  4354. def job_thread_exc(app_obj):
  4355. ret = make_dxf()
  4356. if ret == 'fail':
  4357. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4358. return
  4359. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4360. else:
  4361. ret = make_dxf()
  4362. if ret == 'fail':
  4363. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4364. return
  4365. def import_svg(self, filename, geo_type='geometry', outname=None):
  4366. """
  4367. Adds a new Geometry Object to the projects and populates
  4368. it with shapes extracted from the SVG file.
  4369. :param filename: Path to the SVG file.
  4370. :param outname:
  4371. :return:
  4372. """
  4373. obj_type = ""
  4374. if geo_type is None or geo_type == "geometry":
  4375. obj_type = "geometry"
  4376. elif geo_type == "gerber":
  4377. obj_type = geo_type
  4378. else:
  4379. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4380. "Only Geometry and Gerber are supported")
  4381. return
  4382. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4383. def obj_init(geo_obj, app_obj):
  4384. geo_obj.import_svg(filename, obj_type, units=units)
  4385. geo_obj.multigeo = False
  4386. with self.proc_container.new("Importing SVG") as proc:
  4387. # Object name
  4388. name = outname or filename.split('/')[-1].split('\\')[-1]
  4389. self.new_object(obj_type, name, obj_init, autoselected=False)
  4390. self.progress.emit(20)
  4391. # Register recent file
  4392. self.file_opened.emit("svg", filename)
  4393. # GUI feedback
  4394. self.inform.emit("[success] Opened: " + filename)
  4395. self.progress.emit(100)
  4396. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4397. """
  4398. Adds a new Geometry Object to the projects and populates
  4399. it with shapes extracted from the DXF file.
  4400. :param filename: Path to the DXF file.
  4401. :param outname:
  4402. :type putname: str
  4403. :return:
  4404. """
  4405. obj_type = ""
  4406. if geo_type is None or geo_type == "geometry":
  4407. obj_type = "geometry"
  4408. elif geo_type == "gerber":
  4409. obj_type = geo_type
  4410. else:
  4411. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4412. "Only Geometry and Gerber are supported")
  4413. return
  4414. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4415. def obj_init(geo_obj, app_obj):
  4416. geo_obj.import_dxf(filename, obj_type, units=units)
  4417. geo_obj.multigeo = False
  4418. with self.proc_container.new("Importing DXF") as proc:
  4419. # Object name
  4420. name = outname or filename.split('/')[-1].split('\\')[-1]
  4421. self.new_object(obj_type, name, obj_init, autoselected=False)
  4422. self.progress.emit(20)
  4423. # Register recent file
  4424. self.file_opened.emit("dxf", filename)
  4425. # GUI feedback
  4426. self.inform.emit("[success] Opened: " + filename)
  4427. self.progress.emit(100)
  4428. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4429. """
  4430. Adds a new Geometry Object to the projects and populates
  4431. it with shapes extracted from the SVG file.
  4432. :param filename: Path to the SVG file.
  4433. :param outname:
  4434. :return:
  4435. """
  4436. obj_type = ""
  4437. if type is None or type == "geometry":
  4438. obj_type = "geometry"
  4439. elif type == "gerber":
  4440. obj_type = type
  4441. else:
  4442. self.inform.emit("[error_notcl] Not supported type was picked as parameter. "
  4443. "Only Geometry and Gerber are supported")
  4444. return
  4445. def obj_init(geo_obj, app_obj):
  4446. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4447. geo_obj.multigeo = False
  4448. with self.proc_container.new("Importing Image") as proc:
  4449. # Object name
  4450. name = outname or filename.split('/')[-1].split('\\')[-1]
  4451. units = self.general_options_form.general_app_group.units_radio.get_value()
  4452. self.new_object(obj_type, name, obj_init)
  4453. self.progress.emit(20)
  4454. # Register recent file
  4455. self.file_opened.emit("image", filename)
  4456. # GUI feedback
  4457. self.inform.emit("[success] Opened: " + filename)
  4458. self.progress.emit(100)
  4459. def open_gerber(self, filename, follow=False, outname=None):
  4460. """
  4461. Opens a Gerber file, parses it and creates a new object for
  4462. it in the program. Thread-safe.
  4463. :param outname: Name of the resulting object. None causes the
  4464. name to be that of the file.
  4465. :param filename: Gerber file filename
  4466. :type filename: str
  4467. :param follow: If true, the parser will not create polygons, just lines
  4468. following the gerber path.
  4469. :type follow: bool
  4470. :return: None
  4471. """
  4472. # How the object should be initialized
  4473. def obj_init(gerber_obj, app_obj):
  4474. assert isinstance(gerber_obj, FlatCAMGerber), \
  4475. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4476. # Opening the file happens here
  4477. self.progress.emit(30)
  4478. try:
  4479. gerber_obj.parse_file(filename, follow=follow)
  4480. except IOError:
  4481. app_obj.inform.emit("[error_notcl] Failed to open file: " + filename)
  4482. app_obj.progress.emit(0)
  4483. self.inform.emit('[error_notcl] Failed to open file: ' + filename)
  4484. return "fail"
  4485. except ParseError as err:
  4486. app_obj.inform.emit("[error_notcl] Failed to parse file: " + filename + ". " + str(err))
  4487. app_obj.progress.emit(0)
  4488. self.log.error(str(err))
  4489. return "fail"
  4490. except:
  4491. msg = "[error] An internal error has ocurred. See shell.\n"
  4492. msg += traceback.format_exc()
  4493. app_obj.inform.emit(msg)
  4494. return "fail"
  4495. if gerber_obj.is_empty():
  4496. # app_obj.inform.emit("[error] No geometry found in file: " + filename)
  4497. # self.collection.set_active(gerber_obj.options["name"])
  4498. # self.collection.delete_active()
  4499. self.inform.emit("[error_notcl] Object is not Gerber file or empty. Aborting object creation.")
  4500. return "fail"
  4501. # Further parsing
  4502. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4503. if follow is False:
  4504. App.log.debug("open_gerber()")
  4505. else:
  4506. App.log.debug("open_gerber() with 'follow' attribute")
  4507. with self.proc_container.new("Opening Gerber") as proc:
  4508. self.progress.emit(10)
  4509. # Object name
  4510. name = outname or filename.split('/')[-1].split('\\')[-1]
  4511. ### Object creation ###
  4512. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4513. if ret == 'fail':
  4514. self.inform.emit('[error_notcl] Open Gerber failed. Probable not a Gerber file.')
  4515. return
  4516. # Register recent file
  4517. self.file_opened.emit("gerber", filename)
  4518. self.progress.emit(100)
  4519. # GUI feedback
  4520. self.inform.emit("[success] Opened: " + filename)
  4521. def open_excellon(self, filename, outname=None):
  4522. """
  4523. Opens an Excellon file, parses it and creates a new object for
  4524. it in the program. Thread-safe.
  4525. :param outname: Name of the resulting object. None causes the
  4526. name to be that of the file.
  4527. :param filename: Excellon file filename
  4528. :type filename: str
  4529. :return: None
  4530. """
  4531. App.log.debug("open_excellon()")
  4532. #self.progress.emit(10)
  4533. # How the object should be initialized
  4534. def obj_init(excellon_obj, app_obj):
  4535. # self.progress.emit(20)
  4536. try:
  4537. ret = excellon_obj.parse_file(filename)
  4538. if ret == "fail":
  4539. log.debug("Excellon parsing failed.")
  4540. self.inform.emit("[error_notcl] This is not Excellon file.")
  4541. return "fail"
  4542. except IOError:
  4543. app_obj.inform.emit("[error_notcl] Cannot open file: " + filename)
  4544. log.debug("Could not open Excellon object.")
  4545. self.progress.emit(0) # TODO: self and app_bjj mixed
  4546. return "fail"
  4547. except:
  4548. msg = "[error_notcl] An internal error has occurred. See shell.\n"
  4549. msg += traceback.format_exc()
  4550. app_obj.inform.emit(msg)
  4551. return "fail"
  4552. ret = excellon_obj.create_geometry()
  4553. if ret == 'fail':
  4554. log.debug("Could not create geometry for Excellon object.")
  4555. return "fail"
  4556. if excellon_obj.is_empty():
  4557. app_obj.inform.emit("[error_notcl] No geometry found in file: " + filename)
  4558. return "fail"
  4559. with self.proc_container.new("Opening Excellon."):
  4560. # Object name
  4561. name = outname or filename.split('/')[-1].split('\\')[-1]
  4562. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4563. if ret == 'fail':
  4564. self.inform.emit('[error_notcl] Open Excellon file failed. Probable not an Excellon file.')
  4565. return
  4566. # Register recent file
  4567. self.file_opened.emit("excellon", filename)
  4568. # GUI feedback
  4569. self.inform.emit("[success] Opened: " + filename)
  4570. # self.progress.emit(100)
  4571. def open_gcode(self, filename, outname=None):
  4572. """
  4573. Opens a G-gcode file, parses it and creates a new object for
  4574. it in the program. Thread-safe.
  4575. :param outname: Name of the resulting object. None causes the
  4576. name to be that of the file.
  4577. :param filename: G-code file filename
  4578. :type filename: str
  4579. :return: None
  4580. """
  4581. App.log.debug("open_gcode()")
  4582. # How the object should be initialized
  4583. def obj_init(job_obj, app_obj_):
  4584. """
  4585. :type app_obj_: App
  4586. """
  4587. assert isinstance(app_obj_, App), \
  4588. "Initializer expected App, got %s" % type(app_obj_)
  4589. self.progress.emit(10)
  4590. try:
  4591. f = open(filename)
  4592. gcode = f.read()
  4593. f.close()
  4594. except IOError:
  4595. app_obj_.inform.emit("[error_notcl] Failed to open " + filename)
  4596. self.progress.emit(0)
  4597. return "fail"
  4598. job_obj.gcode = gcode
  4599. self.progress.emit(20)
  4600. ret = job_obj.gcode_parse()
  4601. if ret == "fail":
  4602. self.inform.emit("[error_notcl] This is not GCODE")
  4603. return "fail"
  4604. self.progress.emit(60)
  4605. job_obj.create_geometry()
  4606. with self.proc_container.new("Opening G-Code."):
  4607. # Object name
  4608. name = outname or filename.split('/')[-1].split('\\')[-1]
  4609. # New object creation and file processing
  4610. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  4611. if ret == 'fail':
  4612. self.inform.emit("[error_notcl] Failed to create CNCJob Object. Probable not a GCode file.\n "
  4613. "Attempting to create a FlatCAM CNCJob Object from "
  4614. "G-Code file failed during processing")
  4615. return "fail"
  4616. # Register recent file
  4617. self.file_opened.emit("cncjob", filename)
  4618. # GUI feedback
  4619. self.inform.emit("[success] Opened: " + filename)
  4620. self.progress.emit(100)
  4621. def open_project(self, filename, run_from_arg=None):
  4622. """
  4623. Loads a project from the specified file.
  4624. 1) Loads and parses file
  4625. 2) Registers the file as recently opened.
  4626. 3) Calls on_file_new()
  4627. 4) Updates options
  4628. 5) Calls new_object() with the object's from_dict() as init method.
  4629. 6) Calls plot_all()
  4630. :param filename: Name of the file from which to load.
  4631. :type filename: str
  4632. :return: None
  4633. """
  4634. App.log.debug("Opening project: " + filename)
  4635. # Open and parse
  4636. try:
  4637. f = open(filename, 'r')
  4638. except IOError:
  4639. App.log.error("Failed to open project file: %s" % filename)
  4640. self.inform.emit("[error_notcl] Failed to open project file: %s" % filename)
  4641. return
  4642. try:
  4643. d = json.load(f, object_hook=dict2obj)
  4644. except:
  4645. App.log.error("Failed to parse project file: %s" % filename)
  4646. self.inform.emit("[error_notcl] Failed to parse project file: %s" % filename)
  4647. f.close()
  4648. return
  4649. self.file_opened.emit("project", filename)
  4650. # Clear the current project
  4651. ## NOT THREAD SAFE ##
  4652. if run_from_arg is True:
  4653. pass
  4654. else:
  4655. self.on_file_new()
  4656. #Project options
  4657. self.options.update(d['options'])
  4658. self.project_filename = filename
  4659. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4660. self.set_screen_units(self.options["units"])
  4661. # Re create objects
  4662. App.log.debug("Re-creating objects...")
  4663. for obj in d['objs']:
  4664. def obj_init(obj_inst, app_inst):
  4665. obj_inst.from_dict(obj)
  4666. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  4667. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  4668. # self.plot_all()
  4669. self.inform.emit("[success] Project loaded from: " + filename)
  4670. App.log.debug("Project loaded")
  4671. def propagate_defaults(self, silent=False):
  4672. """
  4673. This method is used to set default values in classes. It's
  4674. an alternative to project options but allows the use
  4675. of values invisible to the user.
  4676. :return: None
  4677. """
  4678. if silent is False:
  4679. self.log.debug("propagate_defaults()")
  4680. # Which objects to update the given parameters.
  4681. routes = {
  4682. "global_zdownrate": CNCjob,
  4683. "excellon_zeros": Excellon,
  4684. "excellon_format_upper_in": Excellon,
  4685. "excellon_format_lower_in": Excellon,
  4686. "excellon_format_upper_mm": Excellon,
  4687. "excellon_format_lower_mm": Excellon,
  4688. "excellon_units": Excellon,
  4689. "gerber_use_buffer_for_union": Gerber,
  4690. "geometry_multidepth": Geometry
  4691. }
  4692. for param in routes:
  4693. if param in routes[param].defaults:
  4694. try:
  4695. routes[param].defaults[param] = self.defaults[param]
  4696. if silent is False:
  4697. self.log.debug(" " + param + " OK")
  4698. except KeyError:
  4699. if silent is False:
  4700. self.log.debug(" ERROR: " + param + " not in defaults.")
  4701. else:
  4702. # Try extracting the name:
  4703. # classname_param here is param in the object
  4704. if param.find(routes[param].__name__.lower() + "_") == 0:
  4705. p = param[len(routes[param].__name__) + 1:]
  4706. if p in routes[param].defaults:
  4707. routes[param].defaults[p] = self.defaults[param]
  4708. if silent is False:
  4709. self.log.debug(" " + param + " OK!")
  4710. def restore_main_win_geom(self):
  4711. try:
  4712. self.ui.setGeometry(self.defaults["global_def_win_x"],
  4713. self.defaults["global_def_win_y"],
  4714. self.defaults["global_def_win_w"],
  4715. self.defaults["global_def_win_h"])
  4716. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  4717. except KeyError:
  4718. pass
  4719. def plot_all(self):
  4720. """
  4721. Re-generates all plots from all objects.
  4722. :return: None
  4723. """
  4724. self.log.debug("Plot_all()")
  4725. for obj in self.collection.get_list():
  4726. def worker_task(obj):
  4727. with self.proc_container.new("Plotting"):
  4728. obj.plot()
  4729. self.object_plotted.emit(obj)
  4730. # Send to worker
  4731. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  4732. # self.progress.emit(10)
  4733. #
  4734. # def worker_task(app_obj):
  4735. # print "worker task"
  4736. # percentage = 0.1
  4737. # try:
  4738. # delta = 0.9 / len(self.collection.get_list())
  4739. # except ZeroDivisionError:
  4740. # self.progress.emit(0)
  4741. # return
  4742. # for obj in self.collection.get_list():
  4743. # with self.proc_container.new("Plotting"):
  4744. # obj.plot()
  4745. # app_obj.object_plotted.emit(obj)
  4746. #
  4747. # percentage += delta
  4748. # self.progress.emit(int(percentage*100))
  4749. #
  4750. # self.progress.emit(0)
  4751. # self.plots_updated.emit()
  4752. #
  4753. # # Send to worker
  4754. # #self.worker.add_task(worker_task, [self])
  4755. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4756. def register_folder(self, filename):
  4757. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  4758. def register_save_folder(self, filename):
  4759. self.defaults['global_last_save_folder'] = os.path.split(str(filename))[0]
  4760. def set_progress_bar(self, percentage, text=""):
  4761. self.ui.progress_bar.setValue(int(percentage))
  4762. def setup_shell(self):
  4763. """
  4764. Creates shell functions. Runs once at startup.
  4765. :return: None
  4766. """
  4767. self.log.debug("setup_shell()")
  4768. def shelp(p=None):
  4769. if not p:
  4770. return "Available commands:\n" + \
  4771. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  4772. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  4773. if p not in commands:
  4774. return "Unknown command: %s" % p
  4775. return commands[p]["help"]
  4776. # --- Migrated to new architecture ---
  4777. # def options(name):
  4778. # ops = self.collection.get_by_name(str(name)).options
  4779. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  4780. def h(*args):
  4781. """
  4782. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  4783. and standalone parameters into list.
  4784. """
  4785. kwa = {}
  4786. a = []
  4787. n = len(args)
  4788. name = None
  4789. for i in range(n):
  4790. match = re.search(r'^-([a-zA-Z].*)', args[i])
  4791. if match:
  4792. assert name is None
  4793. name = match.group(1)
  4794. continue
  4795. if name is None:
  4796. a.append(args[i])
  4797. else:
  4798. kwa[name] = args[i]
  4799. name = None
  4800. return a, kwa
  4801. @contextmanager
  4802. def wait_signal(signal, timeout=10000):
  4803. """
  4804. Block loop until signal emitted, timeout (ms) elapses
  4805. or unhandled exception happens in a thread.
  4806. :param signal: Signal to wait for.
  4807. """
  4808. loop = QtCore.QEventLoop()
  4809. # Normal termination
  4810. signal.connect(loop.quit)
  4811. # Termination by exception in thread
  4812. self.thread_exception.connect(loop.quit)
  4813. status = {'timed_out': False}
  4814. def report_quit():
  4815. status['timed_out'] = True
  4816. loop.quit()
  4817. yield
  4818. # Temporarily change how exceptions are managed.
  4819. oeh = sys.excepthook
  4820. ex = []
  4821. def except_hook(type_, value, traceback_):
  4822. ex.append(value)
  4823. oeh(type_, value, traceback_)
  4824. sys.excepthook = except_hook
  4825. # Terminate on timeout
  4826. if timeout is not None:
  4827. QtCore.QTimer.singleShot(timeout, report_quit)
  4828. #### Block ####
  4829. loop.exec_()
  4830. # Restore exception management
  4831. sys.excepthook = oeh
  4832. if ex:
  4833. self.raiseTclError(str(ex[0]))
  4834. if status['timed_out']:
  4835. raise Exception('Timed out!')
  4836. def make_docs():
  4837. output = ''
  4838. import collections
  4839. od = collections.OrderedDict(sorted(commands.items()))
  4840. for cmd_, val in od.items():
  4841. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  4842. t = val['help']
  4843. usage_i = t.find('>')
  4844. if usage_i < 0:
  4845. expl = t
  4846. output += expl + '\n\n'
  4847. continue
  4848. expl = t[:usage_i - 1]
  4849. output += expl + '\n\n'
  4850. end_usage_i = t[usage_i:].find('\n')
  4851. if end_usage_i < 0:
  4852. end_usage_i = len(t[usage_i:])
  4853. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  4854. else:
  4855. extras = t[usage_i+end_usage_i+1:]
  4856. parts = [s.strip() for s in extras.split('\n')]
  4857. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  4858. for p in parts:
  4859. output += ' ' + p + '\n\n'
  4860. return output
  4861. '''
  4862. Howto implement TCL shell commands:
  4863. All parameters passed to command should be possible to set as None and test it afterwards.
  4864. This is because we need to see error caused in tcl,
  4865. if None value as default parameter is not allowed TCL will return empty error.
  4866. Use:
  4867. def mycommand(name=None,...):
  4868. Test it like this:
  4869. if name is None:
  4870. self.raise_tcl_error('Argument name is missing.')
  4871. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  4872. otherwise we will miss it and processing will silently continue.
  4873. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  4874. which is catched in exec_command and displayed in TCL shell console with red background.
  4875. Error in console is displayed with TCL trace.
  4876. This behavior works only within main thread,
  4877. errors with promissed tasks can be catched and detected only with log.
  4878. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  4879. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  4880. '''
  4881. commands = {
  4882. 'help': {
  4883. 'fcn': shelp,
  4884. 'help': "Shows list of commands."
  4885. },
  4886. }
  4887. # Import/overwrite tcl commands as objects of TclCommand descendants
  4888. # This modifies the variable 'commands'.
  4889. tclCommands.register_all_commands(self, commands)
  4890. # Add commands to the tcl interpreter
  4891. for cmd in commands:
  4892. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  4893. # Make the tcl puts function return instead of print to stdout
  4894. self.tcl.eval('''
  4895. rename puts original_puts
  4896. proc puts {args} {
  4897. if {[llength $args] == 1} {
  4898. return "[lindex $args 0]"
  4899. } else {
  4900. eval original_puts $args
  4901. }
  4902. }
  4903. ''')
  4904. def setup_recent_items(self):
  4905. # TODO: Move this to constructor
  4906. icons = {
  4907. "gerber": "share/flatcam_icon16.png",
  4908. "excellon": "share/drill16.png",
  4909. "cncjob": "share/cnc16.png",
  4910. "project": "share/project16.png",
  4911. "svg": "share/geometry16.png",
  4912. "dxf": "share/dxf16.png",
  4913. "image": "share/image16.png"
  4914. }
  4915. openers = {
  4916. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  4917. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  4918. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  4919. 'project': self.open_project,
  4920. 'svg': self.import_svg,
  4921. 'dxf': self.import_dxf,
  4922. 'image': self.import_image
  4923. }
  4924. # Open file
  4925. try:
  4926. f = open(self.data_path + '/recent.json')
  4927. except IOError:
  4928. App.log.error("Failed to load recent item list.")
  4929. self.inform.emit("[error_notcl] Failed to load recent item list.")
  4930. return
  4931. try:
  4932. self.recent = json.load(f)
  4933. except json.scanner.JSONDecodeError:
  4934. App.log.error("Failed to parse recent item list.")
  4935. self.inform.emit("[error_notcl] Failed to parse recent item list.")
  4936. f.close()
  4937. return
  4938. f.close()
  4939. # Closure needed to create callbacks in a loop.
  4940. # Otherwise late binding occurs.
  4941. def make_callback(func, fname):
  4942. def opener():
  4943. func(fname)
  4944. return opener
  4945. def reset_recent():
  4946. # Reset menu
  4947. self.ui.recent.clear()
  4948. self.recent = []
  4949. try:
  4950. f = open(self.data_path + '/recent.json', 'w')
  4951. except IOError:
  4952. App.log.error("Failed to open recent items file for writing.")
  4953. return
  4954. json.dump(self.recent, f)
  4955. # Reset menu
  4956. self.ui.recent.clear()
  4957. # Create menu items
  4958. for recent in self.recent:
  4959. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  4960. try:
  4961. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  4962. # Attach callback
  4963. o = make_callback(openers[recent["kind"]], recent['filename'])
  4964. action.triggered.connect(o)
  4965. self.ui.recent.addAction(action)
  4966. except KeyError:
  4967. App.log.error("Unsupported file type: %s" % recent["kind"])
  4968. # Last action in Recent Files menu is one that Clear the content
  4969. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  4970. clear_action.triggered.connect(reset_recent)
  4971. self.ui.recent.addSeparator()
  4972. self.ui.recent.addAction(clear_action)
  4973. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  4974. # self.ui.menufilerecent.set_submenu(recent_menu)
  4975. # recent_menu.show_all()
  4976. # self.ui.recent.show()
  4977. self.log.debug("Recent items list has been populated.")
  4978. def setup_component_editor(self):
  4979. label = QtWidgets.QLabel("Choose an item from Project")
  4980. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  4981. self.ui.selected_scroll_area.setWidget(label)
  4982. def setup_obj_classes(self):
  4983. """
  4984. Sets up application specifics on the FlatCAMObj class.
  4985. :return: None
  4986. """
  4987. FlatCAMObj.app = self
  4988. ObjectCollection.app = self
  4989. FCProcess.app = self
  4990. FCProcessContainer.app = self
  4991. def version_check(self):
  4992. """
  4993. Checks for the latest version of the program. Alerts the
  4994. user if theirs is outdated. This method is meant to be run
  4995. in a separate thread.
  4996. :return: None
  4997. """
  4998. self.log.debug("version_check()")
  4999. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5000. full_url = App.version_url + \
  5001. "?s=" + str(self.defaults['global_serial']) + \
  5002. "&v=" + str(self.version) + \
  5003. "&os=" + str(self.os) + \
  5004. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5005. else:
  5006. # no_stats dict; just so it won't break things on website
  5007. no_ststs_dict = {}
  5008. no_ststs_dict["global_ststs"] = {}
  5009. full_url = App.version_url + \
  5010. "?s=" + str(self.defaults['global_serial']) + \
  5011. "&v=" + str(self.version) + \
  5012. "&os=" + str(self.os) + \
  5013. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5014. App.log.debug("Checking for updates @ %s" % full_url)
  5015. ### Get the data
  5016. try:
  5017. f = urllib.request.urlopen(full_url)
  5018. except:
  5019. # App.log.warning("Failed checking for latest version. Could not connect.")
  5020. self.log.warning("Failed checking for latest version. Could not connect.")
  5021. self.inform.emit("[warning_notcl] Failed checking for latest version. Could not connect.")
  5022. return
  5023. try:
  5024. data = json.load(f)
  5025. except Exception as e:
  5026. App.log.error("Could not parse information about latest version.")
  5027. self.inform.emit("[error_notcl] Could not parse information about latest version.")
  5028. App.log.debug("json.load(): %s" % str(e))
  5029. f.close()
  5030. return
  5031. f.close()
  5032. ### Latest version?
  5033. if self.version >= data["version"]:
  5034. App.log.debug("FlatCAM is up to date!")
  5035. self.inform.emit("[success] FlatCAM is up to date!")
  5036. return
  5037. App.log.debug("Newer version available.")
  5038. self.message.emit(
  5039. "Newer Version Available",
  5040. str("There is a newer version of FlatCAM " +
  5041. "available for download:<br><br>" +
  5042. "<B>" + data["name"] + "</b><br>" +
  5043. data["message"].replace("\n", "<br>")),
  5044. "info"
  5045. )
  5046. def on_zoom_fit(self, event):
  5047. """
  5048. Callback for zoom-out request. This can be either from the corresponding
  5049. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5050. with axes limits from the geometry bounds of all objects.
  5051. :param event: Ignored.
  5052. :return: None
  5053. """
  5054. self.plotcanvas.fit_view()
  5055. def disable_all_plots(self):
  5056. self.disable_plots(self.collection.get_list())
  5057. self.inform.emit("[success]All plots disabled.")
  5058. def disable_other_plots(self):
  5059. self.disable_plots(self.collection.get_non_selected())
  5060. self.inform.emit("[success]All non selected plots disabled.")
  5061. def enable_all_plots(self):
  5062. self.enable_plots(self.collection.get_list())
  5063. self.inform.emit("[success]All plots enabled.")
  5064. # TODO: FIX THIS
  5065. '''
  5066. By default this is not threaded
  5067. If threaded the app give warnings like this:
  5068. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5069. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5070. '''
  5071. def enable_plots(self, objects, threaded=False):
  5072. if threaded is True:
  5073. def worker_task(app_obj):
  5074. percentage = 0.1
  5075. try:
  5076. delta = 0.9 / len(objects)
  5077. except ZeroDivisionError:
  5078. self.progress.emit(0)
  5079. return
  5080. for obj in objects:
  5081. obj.options['plot'] = True
  5082. percentage += delta
  5083. self.progress.emit(int(percentage*100))
  5084. self.progress.emit(0)
  5085. self.plots_updated.emit()
  5086. self.collection.update_view()
  5087. # Send to worker
  5088. # self.worker.add_task(worker_task, [self])
  5089. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5090. else:
  5091. for obj in objects:
  5092. obj.options['plot'] = True
  5093. self.progress.emit(0)
  5094. self.plots_updated.emit()
  5095. self.collection.update_view()
  5096. # TODO: FIX THIS
  5097. '''
  5098. By default this is not threaded
  5099. If threaded the app give warnings like this:
  5100. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5101. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5102. '''
  5103. def disable_plots(self, objects, threaded=False):
  5104. # TODO: This method is very similar to replot_all. Try to merge.
  5105. """
  5106. Disables plots
  5107. :param objects: list
  5108. Objects to be disabled
  5109. :return:
  5110. """
  5111. if threaded is True:
  5112. self.progress.emit(10)
  5113. def worker_task(app_obj):
  5114. percentage = 0.1
  5115. try:
  5116. delta = 0.9 / len(objects)
  5117. except ZeroDivisionError:
  5118. self.progress.emit(0)
  5119. return
  5120. for obj in objects:
  5121. obj.options['plot'] = False
  5122. percentage += delta
  5123. self.progress.emit(int(percentage*100))
  5124. self.progress.emit(0)
  5125. self.plots_updated.emit()
  5126. self.collection.update_view()
  5127. # Send to worker
  5128. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5129. else:
  5130. for obj in objects:
  5131. obj.options['plot'] = False
  5132. self.plots_updated.emit()
  5133. self.collection.update_view()
  5134. def clear_plots(self):
  5135. objects = self.collection.get_list()
  5136. for obj in objects:
  5137. obj.clear(obj == objects[-1])
  5138. # Clear pool to free memory
  5139. self.clear_pool()
  5140. def generate_cnc_job(self, objects):
  5141. for obj in objects:
  5142. obj.generatecncjob()
  5143. def save_project(self, filename):
  5144. """
  5145. Saves the current project to the specified file.
  5146. :param filename: Name of the file in which to save.
  5147. :type filename: str
  5148. :return: None
  5149. """
  5150. self.log.debug("save_project()")
  5151. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5152. ## Capture the latest changes
  5153. # Current object
  5154. try:
  5155. self.collection.get_active().read_form()
  5156. except:
  5157. self.log.debug("[warning] There was no active object")
  5158. pass
  5159. # Project options
  5160. self.options_read_form()
  5161. # Serialize the whole project
  5162. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5163. "options": self.options,
  5164. "version": self.version}
  5165. # Open file
  5166. try:
  5167. f = open(filename, 'w')
  5168. except IOError:
  5169. App.log.error("[error] Failed to open file for saving: %s", filename)
  5170. return
  5171. # Write
  5172. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5173. f.close()
  5174. # verification of the saved project
  5175. # Open and parse
  5176. try:
  5177. saved_f = open(filename, 'r')
  5178. except IOError:
  5179. self.inform.emit("[error_notcl] Failed to verify project file: %s. Retry to save it." % filename)
  5180. return
  5181. try:
  5182. saved_d = json.load(saved_f, object_hook=dict2obj)
  5183. except:
  5184. self.inform.emit("[error_notcl] Failed to parse saved project file: %s. Retry to save it." % filename)
  5185. f.close()
  5186. return
  5187. saved_f.close()
  5188. if 'version' in saved_d:
  5189. self.inform.emit("[success] Project saved to: %s" % filename)
  5190. else:
  5191. self.inform.emit("[error_notcl] Failed to save project file: %s. Retry to save it." % filename)
  5192. def on_options_app2project(self):
  5193. """
  5194. Callback for Options->Transfer Options->App=>Project. Copies options
  5195. from application defaults to project defaults.
  5196. :return: None
  5197. """
  5198. self.report_usage("on_options_app2project")
  5199. self.defaults_read_form()
  5200. self.options.update(self.defaults)
  5201. self.options_write_form()
  5202. def on_options_project2app(self):
  5203. """
  5204. Callback for Options->Transfer Options->Project=>App. Copies options
  5205. from project defaults to application defaults.
  5206. :return: None
  5207. """
  5208. self.report_usage("on_options_project2app")
  5209. self.options_read_form()
  5210. self.defaults.update(self.options)
  5211. self.defaults_write_form()
  5212. def on_options_project2object(self):
  5213. """
  5214. Callback for Options->Transfer Options->Project=>Object. Copies options
  5215. from project defaults to the currently selected object.
  5216. :return: None
  5217. """
  5218. self.report_usage("on_options_project2object")
  5219. self.options_read_form()
  5220. obj = self.collection.get_active()
  5221. if obj is None:
  5222. self.inform.emit("WARNING: No object selected.")
  5223. return
  5224. for option in self.options:
  5225. if option.find(obj.kind + "_") == 0:
  5226. oname = option[len(obj.kind) + 1:]
  5227. obj.options[oname] = self.options[option]
  5228. obj.to_form() # Update UI
  5229. def on_options_object2project(self):
  5230. """
  5231. Callback for Options->Transfer Options->Object=>Project. Copies options
  5232. from the currently selected object to project defaults.
  5233. :return: None
  5234. """
  5235. self.report_usage("on_options_object2project")
  5236. obj = self.collection.get_active()
  5237. if obj is None:
  5238. self.inform.emit("WARNING: No object selected.")
  5239. return
  5240. obj.read_form()
  5241. for option in obj.options:
  5242. if option in ['name']: # TODO: Handle this better...
  5243. continue
  5244. self.options[obj.kind + "_" + option] = obj.options[option]
  5245. self.options_write_form()
  5246. def on_options_object2app(self):
  5247. """
  5248. Callback for Options->Transfer Options->Object=>App. Copies options
  5249. from the currently selected object to application defaults.
  5250. :return: None
  5251. """
  5252. self.report_usage("on_options_object2app")
  5253. obj = self.collection.get_active()
  5254. if obj is None:
  5255. self.inform.emit("WARNING: No object selected.")
  5256. return
  5257. obj.read_form()
  5258. for option in obj.options:
  5259. if option in ['name']: # TODO: Handle this better...
  5260. continue
  5261. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5262. self.defaults_write_form()
  5263. def on_options_app2object(self):
  5264. """
  5265. Callback for Options->Transfer Options->App=>Object. Copies options
  5266. from application defaults to the currently selected object.
  5267. :return: None
  5268. """
  5269. self.report_usage("on_options_app2object")
  5270. self.defaults_read_form()
  5271. obj = self.collection.get_active()
  5272. if obj is None:
  5273. self.inform.emit("WARNING: No object selected.")
  5274. return
  5275. for option in self.defaults:
  5276. if option.find(obj.kind + "_") == 0:
  5277. oname = option[len(obj.kind) + 1:]
  5278. obj.options[oname] = self.defaults[option]
  5279. obj.to_form() # Update UI
  5280. # end of file