FlatCAMApp.py 286 KB

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