FlatCAMApp.py 309 KB

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