FlatCAMApp.py 261 KB

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