FlatCAMApp.py 265 KB

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