FlatCAMApp.py 291 KB

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