FlatCAMApp.py 262 KB

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