FlatCAMApp.py 289 KB

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