FlatCAMApp.py 260 KB

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